import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";
import { contactSubmissionsAdapter } from "@/lib/adapters/contacts";

import { getDataSource } from "@/lib/data-source";
import { convexMutation } from "@/lib/convex-client";

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

    const body = await request.json();
    const { contactId, status, internalNotes } = body;

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

    // --- Convex path ---
    if (getDataSource("support") === "convex") {
      try {
        const convexArgs: Record<string, unknown> = {
          id: contactId,
        };

        if (status) {
          convexArgs.status = status.toLowerCase();
          if (status === "RESPONDED") {
            convexArgs.resolved_at = Date.now();
            convexArgs.resolved_by = user.id;
          }
        }

        if (internalNotes !== undefined) {
          convexArgs.notes = internalNotes;
        }

        const updatedId = await convexMutation(
          "support/mutations:updateContactSubmission",
          convexArgs,
        );

        await prisma.audit_logs.create({
          data: {
            userId: user.id,
            type: "staff_action",
            action: "Updated contact",
            success: true,
            ip: request.headers.get("x-forwarded-for") || "0.0.0.0",
            metadata: { contactId, changes: convexArgs },
          },
        });

        return NextResponse.json({ success: true, contact: { id: updatedId } });
      } catch (convexErr) {
        console.error(
          "Convex contact update failed, falling back to Prisma:",
          convexErr,
        );
      }
    }

    // --- Prisma path ---
    const updateData: any = {
      updated_at: new Date(),
    };

    if (status) {
      updateData.status = status.toLowerCase();
      if (status === "RESPONDED") {
        updateData.resolved_at = new Date();
        updateData.resolved_by = user.id;
      }
    }

    if (internalNotes !== undefined) {
      updateData.notes = internalNotes;
    }

    const updatedContact = await prisma.contact_submissions.update({
      where: { id: contactId },
      data: updateData,
    });

    return NextResponse.json({ success: true, contact: updatedContact });
  } catch (error) {
    console.error("Failed to update contact:", error);
    return NextResponse.json(
      { error: "Failed to update contact" },
      { status: 500 },
    );
  }
}
