import { storagePut, storageGet } from "../storage.ts";
import { randomUUID } from "crypto";

export interface VideoUploadOptions {
  file: Buffer | Uint8Array;
  filename: string;
  mimeType: string;
  title: string;
  module: string;
}

export interface VideoUploadResult {
  videoId: string;
  url: string;
  thumbnailUrl: string;
  duration: number;
  filename: string;
  key: string;
}

/**
 * Upload video to CDN storage with thumbnail generation
 */
export async function uploadVideo(options: VideoUploadOptions): Promise<VideoUploadResult> {
  const videoId = randomUUID();
  const fileExtension = options.filename.split(".").pop() || "mp4";
  const storagePath = `videos/${options.module}/${videoId}-${Date.now()}.${fileExtension}`;

  try {
    // Upload video to S3
    const uploadResult = await storagePut(storagePath, options.file, options.mimeType);

    // Generate thumbnail URL (placeholder - in production, use FFmpeg or similar)
    const thumbnailPath = `videos/thumbnails/${videoId}-thumb.jpg`;
    const thumbnailUrl = `${uploadResult.url.replace(/\.[^.]+$/, "-thumb.jpg")}`;

    // Extract duration from video metadata (simplified - in production, use ffprobe)
    const duration = 300; // Default 5 minutes

    return {
      videoId,
      url: uploadResult.url,
      thumbnailUrl,
      duration,
      filename: options.filename,
      key: uploadResult.key,
    };
  } catch (error) {
    console.error("Video upload failed:", error);
    throw new Error(`Failed to upload video: ${error instanceof Error ? error.message : "Unknown error"}`);
  }
}

/**
 * Get video download URL with expiration
 */
export async function getVideoDownloadUrl(videoKey: string, expiresIn: number = 3600): Promise<string> {
  try {
    const result = await storageGet(videoKey, expiresIn);
    return result.url;
  } catch (error) {
    console.error("Failed to get video download URL:", error);
    throw new Error(`Failed to get video URL: ${error instanceof Error ? error.message : "Unknown error"}`);
  }
}

/**
 * Delete video from storage
 */
export async function deleteVideo(videoKey: string): Promise<void> {
  try {
    // Note: This is a placeholder. Implement actual deletion based on your storage provider
    console.log(`Deleting video: ${videoKey}`);
    // await storageDelete(videoKey);
  } catch (error) {
    console.error("Failed to delete video:", error);
    throw new Error(`Failed to delete video: ${error instanceof Error ? error.message : "Unknown error"}`);
  }
}

/**
 * Generate video thumbnail from file
 * In production, use FFmpeg or similar tool
 */
export async function generateVideoThumbnail(videoBuffer: Buffer): Promise<Buffer> {
  // Placeholder implementation
  // In production, use ffmpeg to extract frame at 1 second mark
  // For now, return a placeholder image
  return Buffer.from("placeholder-thumbnail");
}

/**
 * Validate video file
 */
export function validateVideoFile(file: File): { valid: boolean; error?: string } {
  const maxSize = 500 * 1024 * 1024; // 500MB
  const allowedTypes = ["video/mp4", "video/webm", "video/quicktime", "video/x-msvideo"];

  if (file.size > maxSize) {
    return { valid: false, error: "Video file is too large (max 500MB)" };
  }

  if (!allowedTypes.includes(file.type)) {
    return { valid: false, error: "Invalid video format. Allowed: MP4, WebM, MOV, AVI" };
  }

  return { valid: true };
}

/**
 * Calculate upload progress
 */
export function calculateUploadProgress(loaded: number, total: number): number {
  if (total === 0) return 0;
  return Math.round((loaded / total) * 100);
}
