import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { deleteAllContacts } from "@/lib/services/contact.service";
import { getDataSource } from "@/lib/data-source";
import { convexQuery, convexMutation } from "@/lib/convex-client";

export async function DELETE(request: NextRequest) {
  try {
    const user = await requireStaffAuth();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Admin-only operation
    if (user.role !== "ADMIN" && user.role !== "SUPER_ADMIN") {
      return NextResponse.json(
        { error: "Forbidden: Admin role required for bulk deletion" },
        { status: 403 },
      );
    }

    // Get confirmation token from request body
    const body = await request.json();
    const { confirmationToken } = body;

    // Require confirmation token matching "DELETE ALL"
    if (confirmationToken !== "DELETE ALL") {
      return NextResponse.json(
        { error: 'Invalid confirmation token. Type "DELETE ALL" to confirm.' },
        { status: 400 },
      );
    }

    // --- Convex path ---
    if (getDataSource("support") === "convex") {
      try {
        // Fetch all contact submissions then delete each
        const allSubmissions = await convexQuery(
          "support/queries:getContactSubmissions",
          { limit: 10000 },
        );
        const submissions =
          (allSubmissions as Array<Record<string, unknown>>) ?? [];
        let deletedCount = 0;

        for (const submission of submissions) {
          await convexMutation("support/mutations:deleteContactSubmission", {
            id: submission._id as any,
          });
          deletedCount++;
        }

        return NextResponse.json({
          success: true,
          message: `Successfully deleted ${deletedCount} contact(s)`,
          count: deletedCount,
        });
      } catch (convexErr) {
        console.error(
          "Convex delete-all contacts failed, falling back to Prisma:",
          convexErr,
        );
      }
    }

    // --- Prisma path ---
    const result = await deleteAllContacts(user.id);

    if (result.success) {
      return NextResponse.json({
        success: true,
        message: `Successfully deleted ${result.count} contact(s)`,
        count: result.count,
      });
    } else {
      return NextResponse.json({ error: result.error }, { status: 500 });
    }
  } catch (error) {
    console.error("Failed to delete all contacts:", error);
    return NextResponse.json(
      { error: "Failed to delete all contacts" },
      { status: 500 },
    );
  }
}
