import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

const SUPABASE_URL = Deno.env.get("SUPABASE_URL") ?? "";
const SUPABASE_ANON_KEY = Deno.env.get("SUPABASE_ANON_KEY") ?? "";
const SUNO_BEARER_TOKEN = Deno.env.get("SUNO_BEARER_TOKEN") ?? "";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers":
    "authorization, x-client-info, apikey, content-type",
};

Deno.serve(async (req: Request) => {
  if (req.method === "OPTIONS") {
    return new Response("ok", { headers: corsHeaders });
  }

  if (req.method !== "POST") {
    return new Response("Method Not Allowed", {
      status: 405,
      headers: corsHeaders,
    });
  }

  const authHeader = req.headers.get("Authorization");
  if (!authHeader) {
    return new Response("Unauthorized", { status: 401, headers: corsHeaders });
  }

  const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
    global: { headers: { Authorization: authHeader } },
  });

  const token = authHeader.replace("Bearer ", "");
  const { data: userData, error: userError } = await supabase.auth.getUser(
    token
  );
  if (userError || !userData?.user) {
    return new Response("Unauthorized", { status: 401, headers: corsHeaders });
  }
  const user_id = userData.user.id;

  let body;
  try {
    body = await req.json();
  } catch {
    return new Response("Invalid JSON", { status: 400, headers: corsHeaders });
  }
  const { room_id, prompt_id } = body;
  if (!room_id || !prompt_id) {
    return new Response("Missing room_id or prompt_id", {
      status: 400,
      headers: corsHeaders,
    });
  }

  // Fetch prompt metadata
  const { data: prompt, error: promptError } = await supabase
    .from("prompt_queue")
    .select("prompt_json")
    .eq("id", prompt_id)
    .single();
  if (promptError || !prompt) {
    return new Response("Prompt not found", {
      status: 404,
      headers: corsHeaders,
    });
  }

  // Call Suno API
  const sunoRes = await fetch(
    "https://studio-api.staging.suno.com/api/generate/v2-web/",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${SUNO_BEARER_TOKEN}`,
      },
      body: JSON.stringify(prompt.prompt_json),
    }
  );
  if (!sunoRes.ok) {
    return new Response("Suno API error", {
      status: 502,
      headers: corsHeaders,
    });
  }
  const sunoData = await sunoRes.json();
  if (!sunoData.clips || !Array.isArray(sunoData.clips)) {
    return new Response("Invalid Suno response", {
      status: 502,
      headers: corsHeaders,
    });
  }

  // Upsert only the first clip
  const firstClip = sunoData.clips[0];
  if (firstClip) {
    await supabase.from("clips").upsert({
      id: firstClip.id,
      user_id,
      radio_room_id: room_id,
      metadata: firstClip,
      status: firstClip.status,
    });
  }

  // Poll for status updates in the background
  EdgeRuntime.waitUntil(
    (async () => {
      let incomplete = firstClip ? [firstClip.id] : [];
      while (incomplete.length > 0) {
        console.log("Polling Suno feed for clip ids:", incomplete);
        await new Promise((r) => setTimeout(r, 5000));
        const feedRes = await fetch(
          `https://studio-api.staging.suno.com/api/feed/v2/?ids=${incomplete.join(
            ","
          )}`,
          {
            headers: {
              Authorization: `Bearer ${SUNO_BEARER_TOKEN}`,
            },
          }
        );
        if (!feedRes.ok) break;
        const feedData = await feedRes.json();
        for (const clip of feedData.clips || []) {
          await supabase
            .from("clips")
            .update({
              metadata: clip,
              status: clip.status,
            })
            .eq("id", clip.id);
        }
        incomplete = (feedData.clips || [])
          .filter((c: any) => c.status !== "complete")
          .map((c: any) => c.id);
      }
    })()
  );

  return new Response(
    JSON.stringify({ ok: true, ids: firstClip ? [firstClip.id] : [] }),
    {
      headers: { ...corsHeaders, "Content-Type": "application/json" },
      status: 200,
    }
  );
});
