import { NextResponse } from "next/server";
import { getDbPool } from "@/db";
import { getSession } from "@/lib/auth";
import { resolveInspectionTenant } from "@/lib/authorization";

export const runtime = "nodejs";

export async function POST(request: Request, { params }: { params: Promise<{ externalId: string }> }) {
  try {
    const session = await getSession();
    if (!session) return NextResponse.json({ error: "Faça login para gerenciar a lixeira." }, { status: 401 });
    if (session.role.startsWith("client_")) return NextResponse.json({ error: "A lixeira é gerenciada pela operação Capital." }, { status: 403 });
    const { externalId } = await params;
    const { action, tenantId: requestedTenantId } = await request.json().catch(() => ({ action: "trash" }));
    if (!["trash", "restore"].includes(String(action))) return NextResponse.json({ error: "Ação de lixeira inválida." }, { status: 400 });
    const tenantId = await resolveInspectionTenant(session, String(requestedTenantId || ""));
    if (!tenantId) return NextResponse.json({ error: "Cliente da vistoria não encontrado ou inativo." }, { status: 404 });
    const db = getDbPool();
    const [rows] = await db.execute("SELECT id, status FROM inspections WHERE tenant_id = ? AND external_id = ? LIMIT 1", [tenantId, externalId]);
    const inspection = (rows as { id: string; status: string }[])[0];
    if (!inspection) return NextResponse.json({ error: "Vistoria não encontrada." }, { status: 404 });

    if (action === "trash") {
      if (inspection.status === "trashed") return NextResponse.json({ message: "Esta vistoria já está na lixeira." });
      await db.execute("UPDATE inspection_access_links SET revoked_at = NOW() WHERE inspection_id = ? AND revoked_at IS NULL", [inspection.id]);
      await db.execute("UPDATE inspections SET status = 'trashed', trashed_at = NOW(), trashed_by = ? WHERE id = ?", [session.name, inspection.id]);
      return NextResponse.json({ message: "Vistoria movida para a lixeira. Os links ativos foram revogados." });
    }

    if (inspection.status !== "trashed") return NextResponse.json({ error: "Esta vistoria não está na lixeira." }, { status: 409 });
    await db.execute("UPDATE inspections SET status = 'received', trashed_at = NULL, trashed_by = NULL, completed_at = NULL WHERE id = ?", [inspection.id]);
    return NextResponse.json({ message: "Vistoria restaurada. Gere um novo link antes de enviá-la ao responsável." });
  } catch (error) {
    console.error("Erro ao gerenciar lixeira da vistoria", error);
    const code = (error as { code?: string }).code;
    if (code === "ER_BAD_FIELD_ERROR" || code === "WARN_DATA_TRUNCATED") return NextResponse.json({ error: "A lixeira ainda não foi instalada no banco.", hint: "Execute a migration 011_inspection_trash.sql e tente novamente." }, { status: 503 });
    return NextResponse.json({ error: "Não foi possível atualizar a lixeira." }, { status: 500 });
  }
}
