import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { canUseElevatedAccess } from "@/lib/elevated-access";

type CleanupBody = {
  target?: "logs";
};

export async function POST(request: Request) {
  const session = await getServerSession(authOptions);
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const canRunCleanup = session.user.role === "owner" || canUseElevatedAccess(session.user.email);
  if (!canRunCleanup) {
    return NextResponse.json({ error: "Only owners or elevated admins can run cleanup." }, { status: 403 });
  }

  const body = (await request.json().catch(() => ({}))) as CleanupBody;
  if (body.target !== "logs") {
    return NextResponse.json({ error: "Invalid cleanup target." }, { status: 400 });
  }

  const [
    marketingSyncRuns,
    marketingInitiativeEdits,
    reminderEvents,
    passwordResetTokens,
    verificationTokens,
    staleSessions,
    invitations,
  ] = await prisma.$transaction([
    prisma.marketingSyncRun.deleteMany({}),
    prisma.marketingInitiativeEdit.deleteMany({}),
    prisma.reminderEvent.deleteMany({}),
    prisma.passwordResetToken.deleteMany({}),
    prisma.verificationToken.deleteMany({}),
    prisma.session.deleteMany({
      where: {
        userId: {
          not: session.user.id,
        },
      },
    }),
    prisma.invitation.deleteMany({}),
  ]);

  return NextResponse.json({
    ok: true,
    deleted: {
      marketingSyncRuns: marketingSyncRuns.count,
      marketingInitiativeEdits: marketingInitiativeEdits.count,
      reminderEvents: reminderEvents.count,
      passwordResetTokens: passwordResetTokens.count,
      verificationTokens: verificationTokens.count,
      sessions: staleSessions.count,
      invitations: invitations.count,
    },
  });
}
