import { NextResponse } from "next/server";

import { livesGuardadas as guardadas, type LiveNaVitrine } from "@/lib/live/servidor/vitrine";
import { createAdminClient } from "@/lib/supabase-admin";

export const runtime = "nodejs";

/*
 * Liveshop: as lives da loja que estão no ar agora e aparecem nas páginas dos
 * produtos. Só o que a vitrine precisa (nada de canal nem de participante).
 */
export async function GET(req: Request) {
  const url = new URL(req.url);
  const slug = String(url.searchParams.get("loja") || "").trim().toLowerCase().slice(0, 120);
  const cabecalhos = { "cache-control": "no-store" };
  if (!slug || !/^[a-z0-9-]+$/.test(slug)) return NextResponse.json({ lives: [] }, { headers: cabecalhos });

  const guardada = guardadas.get(slug);
  if (guardada && Date.now() - guardada.em < 20000) return NextResponse.json({ lives: guardada.lives }, { headers: cabecalhos });

  let lives: LiveNaVitrine[] = [];
  try {
    const admin = createAdminClient();
    const { data: perfil } = await admin.from("profiles").select("id").eq("slug", slug).maybeSingle();
    const lojaId = (perfil as { id?: string } | null)?.id;
    if (lojaId) {
      const { data } = await admin
        .from("live_salas")
        .select("id,titulo,acesso,produtos_vitrine,product_id,estado")
        .eq("user_id", lojaId)
        .eq("status", "ao_vivo")
        .eq("vitrine", true)
        .limit(3);
      const salas = (data ?? []) as Array<{ id: string; titulo: string; acesso: LiveNaVitrine["acesso"]; produtos_vitrine: string[] | null; product_id: string | null; estado: Record<string, unknown> | null }>;
      const capas = new Map<string, string | null>();
      const produtosDasLives = salas.map((s) => s.product_id).filter((id): id is string => Boolean(id));
      if (produtosDasLives.length) {
        const { data: produtos } = await admin.from("products").select("id,image_url").in("id", produtosDasLives);
        for (const p of (produtos ?? []) as Array<{ id: string; image_url: string | null }>) capas.set(p.id, p.image_url);
      }
      lives = salas.map((s) => {
        const foco = s.estado && typeof s.estado === "object" ? (s.estado.foco as { id?: unknown } | undefined) : undefined;
        const idDoFoco = typeof foco?.id === "string" && foco.id.startsWith("p-") ? foco.id.slice(2) : null;
        return {
          salaId: s.id,
          titulo: s.titulo,
          acesso: s.acesso,
          produtos: (s.produtos_vitrine ?? []).slice(0, 40),
          produtoDaLive: s.product_id,
          capa: s.product_id ? capas.get(s.product_id) ?? null : null,
          foco: idDoFoco,
        };
      });
    }
  } catch {
    lives = [];
  }
  guardadas.set(slug, { em: Date.now(), lives });
  if (guardadas.size > 2000) guardadas.delete(guardadas.keys().next().value as string);
  return NextResponse.json({ lives }, { headers: cabecalhos });
}
