import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { archivos } from "@/lib/schema";
import { eq, and } from "drizzle-orm";

const BRIDGE_URL = (process.env.EVOLUTION_API_URL ?? "").trim();
const BRIDGE_KEY = (process.env.EVOLUTION_API_KEY ?? "").trim();

async function uploadToBridge(
  buffer: Buffer,
  mimetype: string,
  filename: string
): Promise<string> {
  const base64 = buffer.toString("base64");
  const res = await fetch(`${BRIDGE_URL}/media/upload`, {
    method: "POST",
    headers: { "Content-Type": "application/json", apikey: BRIDGE_KEY },
    body: JSON.stringify({ base64, mimetype, filename }),
  });
  if (!res.ok) throw new Error(`Bridge upload failed: ${await res.text()}`);
  const data = await res.json();
  return data.url as string;
}

export async function GET(req: Request) {
  const session = await auth();
  if (!session) return Response.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const seccion = searchParams.get("seccion");
  const referenciaId = searchParams.get("referenciaId");

  if (!seccion || !referenciaId) {
    return Response.json({ error: "seccion and referenciaId required" }, { status: 400 });
  }

  const rows = await db.select().from(archivos)
    .where(and(
      eq(archivos.seccion, seccion),
      eq(archivos.referenciaId, parseInt(referenciaId))
    ));

  return Response.json(rows);
}

export async function POST(req: Request) {
  const session = await auth();
  if (!session) return Response.json({ error: "Unauthorized" }, { status: 401 });
  if (session.user.role !== "admin") return Response.json({ error: "Forbidden" }, { status: 403 });

  const formData = await req.formData();
  const file = formData.get("file") as File | null;
  const tipo = formData.get("tipo") as string;
  const seccion = formData.get("seccion") as string;
  const referenciaId = formData.get("referenciaId") as string;
  const periodo = formData.get("periodo") as string | null;

  if (!file || !tipo || !seccion || !referenciaId) {
    return Response.json({ error: "file, tipo, seccion, referenciaId required" }, { status: 400 });
  }

  if (!["recibo", "factura"].includes(tipo)) {
    return Response.json({ error: "tipo must be recibo or factura" }, { status: 400 });
  }

  const buffer = Buffer.from(await file.arrayBuffer());
  const ext = file.name.split(".").pop() || "bin";
  const filename = `${seccion}_${referenciaId}_${tipo}_${Date.now()}.${ext}`;

  let storagePath: string;
  try {
    storagePath = await uploadToBridge(buffer, file.type, filename);
  } catch (err) {
    console.error("File upload error:", err);
    return Response.json({ error: "Failed to upload file" }, { status: 500 });
  }

  const [row] = await db.insert(archivos).values({
    tipo,
    seccion,
    referenciaId: parseInt(referenciaId),
    periodo: periodo || null,
    nombreArchivo: file.name,
    storagePath,
    contentType: file.type,
    sizeBytes: file.size,
    subidoPor: session.user.email,
  }).returning();

  return Response.json(row, { status: 201 });
}
