import { corsHeaders, handleCors } from "../_shared/cors.ts";
import { verifyAdmin, AuthError } from "../_shared/auth.ts";
import { createServiceClient } from "../_shared/supabase-client.ts";
import {
  parsePlaylistId,
  getPlaylistItems,
  classifyGenres,
} from "../_shared/youtube-client.ts";

Deno.serve(async (req: Request) => {
  // Handle CORS preflight
  const corsResponse = handleCors(req);
  if (corsResponse) return corsResponse;

  try {
    // Only accept POST
    if (req.method !== "POST") {
      return new Response(JSON.stringify({ error: "Method not allowed" }), {
        status: 405,
        headers: { ...corsHeaders, "Content-Type": "application/json" },
      });
    }

    // Verify admin auth
    const userId = await verifyAdmin(req);

    // Parse request body
    const { playlistUrl, genre } = await req.json();
    if (!playlistUrl || typeof playlistUrl !== "string") {
      return new Response(
        JSON.stringify({ error: "playlistUrl is required" }),
        {
          status: 400,
          headers: { ...corsHeaders, "Content-Type": "application/json" },
        }
      );
    }

    // Validate the URL format
    parsePlaylistId(playlistUrl);

    // Fetch playlist metadata via the sidecar worker
    const playlist = await getPlaylistItems(playlistUrl);

    if (playlist.items.length === 0) {
      return new Response(
        JSON.stringify({ error: "Playlist is empty or could not be loaded" }),
        {
          status: 400,
          headers: { ...corsHeaders, "Content-Type": "application/json" },
        }
      );
    }

    // Create the download job in the database
    const supabase = createServiceClient();

    // Auto-classify genres via YouTube metadata + Gemini (best-effort).
    // Only runs when no manual genre was provided — manual genre overrides all.
    let classifiedGenres: Record<string, string> = {};
    if (!genre) {
      classifiedGenres = await classifyGenres(
        playlist.items.map((item) => ({
          videoId: item.videoId,
          title: item.title,
          author: item.author ?? null,
        }))
      );
    }

    const { data: job, error: jobError } = await supabase
      .from("download_jobs")
      .insert({
        playlist_url: playlistUrl,
        playlist_title: playlist.title,
        status: "pending",
        total_items: playlist.items.length,
        completed_items: 0,
        failed_items: 0,
        created_by: userId,
      })
      .select()
      .single();

    if (jobError || !job) {
      throw new Error(`Failed to create download job: ${jobError?.message}`);
    }

    // Create download items for each video
    // Priority: manual genre > auto-classified genre > null
    const itemRows = playlist.items.map((item) => ({
      job_id: job.id,
      video_id: item.videoId,
      title: item.title,
      duration_seconds: item.durationSeconds,
      thumbnail_url: item.thumbnailUrl,
      status: "pending",
      genre: genre || classifiedGenres[item.videoId] || null,
    }));

    const { error: itemsError } = await supabase
      .from("download_items")
      .insert(itemRows);

    if (itemsError) {
      await supabase.from("download_jobs").delete().eq("id", job.id);
      throw new Error(`Failed to create download items: ${itemsError.message}`);
    }

    // Fetch the created items to return
    const { data: items } = await supabase
      .from("download_items")
      .select("*")
      .eq("job_id", job.id)
      .order("created_at", { ascending: true });

    return new Response(
      JSON.stringify({
        jobId: job.id,
        playlistTitle: playlist.title,
        totalItems: playlist.items.length,
        items: items ?? [],
      }),
      {
        status: 200,
        headers: { ...corsHeaders, "Content-Type": "application/json" },
      }
    );
  } catch (error) {
    const status = error instanceof AuthError ? error.status : 500;
    const message =
      error instanceof Error ? error.message : "Unknown error occurred";

    return new Response(JSON.stringify({ error: message }), {
      status,
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  }
});
