import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getSessionUser } from "@/lib/auth";
import { deleteFromR2 } from "@/lib/r2";

export async function DELETE() {
  const session = await getSessionUser();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  // Get all files for the user
  const files = await prisma.file.findMany({
    where: { userId: session.userId },
    select: { id: true, key: true },
  });

  if (files.length === 0) {
    return NextResponse.json({ ok: true, deleted: 0 });
  }

  // Delete all files from R2
  const deletePromises = files.map((file) => deleteFromR2(file.key));
  await Promise.all(deletePromises);

  // Delete all file records from database
  await prisma.file.deleteMany({
    where: { userId: session.userId },
  });

  return NextResponse.json({ ok: true, deleted: files.length });
}

