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

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

async function deleteFromBridge(url: string): Promise<void> {
  const filename = url.split("/").pop();
  if (!filename) return;
  const res = await fetch(`${BRIDGE_URL}/media/${filename}`, {
    method: "DELETE",
    headers: { apikey: BRIDGE_KEY },
  });
  if (!res.ok) console.error("Bridge delete failed:", await res.text());
}

export async function DELETE(req: Request, { params }: { params: Promise<{ id: string }> }) {
  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 { id } = await params;
  const numId = parseInt(id);
  if (isNaN(numId) || numId <= 0) return Response.json({ error: "Invalid ID" }, { status: 400 });

  const [row] = await db.select().from(archivos)
    .where(eq(archivos.id, numId)).limit(1);

  if (!row) return Response.json({ error: "Not found" }, { status: 404 });

  // Delete from Oracle VM (storagePath is a full URL for new files)
  if (row.storagePath.startsWith("http")) {
    await deleteFromBridge(row.storagePath);
  }

  await db.delete(archivos).where(eq(archivos.id, numId));

  return Response.json({ success: true });
}
