import { NextResponse } from "next/server";

import { linkGuardado } from "@/lib/digitais/curso";
import { enderecoParaBaixar, configuracaoDoR2 } from "@/lib/digitais/r2";
import { acessoAAula } from "@/lib/digitais/servidor/curso";
import { createAdminClient } from "@/lib/supabase-admin";

/*
 * O vídeo de uma aula para quem pode assistir agora: o endereço assinado do
 * depósito (6 horas; o player pede outro sozinho se vencer no meio) ou o
 * endereço de incorporação do YouTube/Vimeo/Panda. Aula travada não assina.
 */

const SEIS_HORAS = 6 * 60 * 60;

export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const semCache = { headers: { "cache-control": "no-store" } };
  try {
    const { id } = await params;
    const slug = String(new URL(request.url).searchParams.get("slug") || "").trim().toLowerCase();
    if (!slug) return NextResponse.json({ error: "Vídeo inválido." }, { status: 400, ...semCache });

    const admin = createAdminClient();
    const acesso = await acessoAAula(admin, { slug, aulaId: id });
    if (!acesso.ok) return NextResponse.json({ error: acesso.motivo }, { status: acesso.status, ...semCache });
    const { aula } = acesso;
    if (aula.tipo !== "video") return NextResponse.json({ error: "Este item não tem vídeo." }, { status: 404, ...semCache });

    const link = linkGuardado(aula.video_link);
    if (link) return NextResponse.json({ ok: true, tipo: "link", provedor: link.provedor, url: link.url }, semCache);

    const arquivo = aula.digital_files;
    if (!arquivo || arquivo.status !== "pronto") return NextResponse.json({ error: "Este vídeo ainda está sendo preparado." }, { status: 409, ...semCache });
    const cfg = configuracaoDoR2();
    if (!cfg) return NextResponse.json({ error: "Os vídeos estão indisponíveis agora. Tente em alguns minutos." }, { status: 503, ...semCache });
    const url = enderecoParaBaixar(cfg, arquivo.storage_key, { nome: arquivo.nome, segundos: SEIS_HORAS, abrirNoNavegador: true, tipo: arquivo.mime });
    return NextResponse.json({ ok: true, tipo: "arquivo", url, expiraEm: new Date(Date.now() + SEIS_HORAS * 1000).toISOString() }, semCache);
  } catch (erro) {
    console.error("[digitais] video da aula", erro);
    return NextResponse.json({ error: "Não foi possível abrir o vídeo agora." }, { status: 500, ...semCache });
  }
}
