import { prisma } from "@/lib/prisma";
import { getAdminUser } from "@/lib/auth";
import { NextRequest, NextResponse } from "next/server";

const ALLOWED_STATUSES = ["Pending", "Replied", "Resolved", "Spam"];

export async function DELETE(
  _req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ success: false }, { status: 401 });

  const { id: rawId } = await params;
  const id = BigInt(rawId);

  const existing = await prisma.contact_enquiries.findUnique({ where: { id } });
  if (!existing) {
    return NextResponse.json(
      { success: false, message: "Enquiry not found" },
      { status: 404 }
    );
  }

  await prisma.contact_enquiries.delete({ where: { id } });

  return NextResponse.json({ success: true, message: "Enquiry deleted successfully" });
}

// PATCH /api/admin/contact-enquiries/:id — update status (e.g. mark as
// Replied once the admin has responded via their own mail client) and/or
// admin_notes. The reply content itself is never sent through this app.
export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ success: false }, { status: 401 });

  const { id: rawId } = await params;
  const id = BigInt(rawId);

  const existing = await prisma.contact_enquiries.findUnique({ where: { id } });
  if (!existing) {
    return NextResponse.json(
      { success: false, message: "Enquiry not found" },
      { status: 404 }
    );
  }

  const body = await req.json().catch(() => ({}));
  const { status, admin_notes } = body as { status?: string; admin_notes?: string };

  if (status !== undefined && !ALLOWED_STATUSES.includes(status)) {
    return NextResponse.json(
      { success: false, message: `Status must be one of: ${ALLOWED_STATUSES.join(", ")}` },
      { status: 400 }
    );
  }

  const updated = await prisma.contact_enquiries.update({
    where: { id },
    data: {
      ...(status !== undefined ? { status } : {}),
      ...(admin_notes !== undefined ? { admin_notes } : {}),
      updated_at: new Date(),
    },
  });

  return NextResponse.json({
    success: true,
    message: "Enquiry updated successfully",
    data: { ...updated, id: updated.id.toString() },
  });
}