import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { deleteContact } from "@/lib/services/contact.service";
import { getDataSource } from "@/lib/data-source";
import { 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 });
    }

    const { searchParams } = new URL(request.url);
    const contactId = searchParams.get("id");

    if (!contactId) {
      return NextResponse.json(
        { error: "Contact ID required" },
        { status: 400 },
      );
    }

    // --- Convex path ---
    if (getDataSource("support") === "convex") {
      try {
        await convexMutation("support/mutations:deleteContactSubmission", {
          id: contactId as any,
        });
        return NextResponse.json({
          success: true,
          message: "Contact deleted successfully",
        });
      } catch (convexErr) {
        console.error(
          "Convex contact delete failed, falling back to Prisma:",
          convexErr,
        );
      }
    }

    // --- Prisma path ---
    const result = await deleteContact(contactId, user.id);

    if (result.success) {
      return NextResponse.json({
        success: true,
        message: "Contact deleted successfully",
      });
    } else {
      return NextResponse.json({ error: result.error }, { status: 500 });
    }
  } catch (error) {
    console.error("Failed to delete contact:", error);
    return NextResponse.json(
      { error: "Failed to delete contact" },
      { status: 500 },
    );
  }
}
