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 { convexQuery } from "@/lib/convex-client";

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

    const { searchParams } = new URL(request.url);
    const status = searchParams.get("status");
    const search = searchParams.get("search");

    // --- Convex path ---
    if (getDataSource("support") === "convex") {
      try {
        const submissions = await convexQuery(
          "support/queries:getContactSubmissions",
          {
            status: status && status !== "all" ? status : undefined,
            limit: 100,
            search: search || undefined,
          },
        );

        const contacts = (
          (submissions as Array<Record<string, unknown>>) ?? []
        ).map((submission) => ({
          id: submission._id ?? submission.id,
          name: submission.name,
          email: submission.email,
          phone: submission.phone,
          company: submission.company,
          message: submission.message,
          language: submission.preferred_language,
          status:
            typeof submission.status === "string"
              ? submission.status.toUpperCase()
              : "NEW",
          createdAt: submission.created_at
            ? new Date(submission.created_at as number).toISOString()
            : null,
          updatedAt: submission.updated_at
            ? new Date(submission.updated_at as number).toISOString()
            : null,
          respondedAt: submission.resolved_at
            ? new Date(submission.resolved_at as number).toISOString()
            : null,
          respondedBy: submission.resolved_by || null,
          internalNotes: submission.notes || null,
          assignedTo: null,
          assignedStaff: null,
        }));

        return NextResponse.json({ contacts });
      } catch (convexErr) {
        console.error(
          "Convex contact fetch failed, falling back to Prisma:",
          convexErr,
        );
      }
    }

    // --- Prisma path ---
    const where: any = {};

    if (status && status !== "all") {
      where.status = status;
    }

    if (search) {
      where.OR = [
        { name: { contains: search, mode: "insensitive" } },
        { email: { contains: search, mode: "insensitive" } },
        { company: { contains: search, mode: "insensitive" } },
      ];
    }

    const submissions = await contactSubmissionsAdapter.findMany({
      where,
      orderBy: { created_at: "desc" },
      take: 100,
    });

    // Transform snake_case database fields to camelCase for frontend
    const contacts = submissions.map((submission) => ({
      id: submission.id,
      name: submission.name,
      email: submission.email,
      phone: submission.phone,
      company: submission.company,
      message: submission.message,
      language: submission.preferred_language,
      status: submission.status.toUpperCase(),
      createdAt: submission.created_at.toISOString(),
      updatedAt: submission.updated_at.toISOString(),
      respondedAt: submission.resolved_at?.toISOString() || null,
      respondedBy: submission.resolved_by || null,
      internalNotes: submission.notes || null,
      assignedTo: null,
      assignedStaff: null,
    }));

    return NextResponse.json({ contacts });
  } catch (error) {
    console.error("Failed to fetch contacts:", error);
    return NextResponse.json(
      { error: "Failed to fetch contacts" },
      { status: 500 },
    );
  }
}
