/**
 * Staff Support Tickets API
 * GET /api/staff/dashboard/support - List tickets (staff view) or get metrics
 *
 * Convex-first with Prisma fallback.
 */

import { NextRequest, NextResponse } from "next/server";
import { validateStaffSession } from "@/lib/staff-session";
import {
  getTickets,
  getTicketMetrics,
  type TicketFilters,
  type TicketStatus,
  type TicketPriority,
  type TicketCategory,
} from "@/lib/services/support-tickets.service";
import { convexQuery } from "@/lib/convex-client";

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

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

    // --- Convex-first path ---
    try {
      // Get metrics
      if (action === "metrics") {
        const metrics = await convexQuery(
          "support/queries:getTicketMetrics",
          {},
        );
        if (metrics !== null) {
          return NextResponse.json(metrics);
        }
      } else {
        // Get paginated tickets
        const status = searchParams.get("status");
        const priority = searchParams.get("priority");
        const category = searchParams.get("category");
        const search = searchParams.get("search");
        const page = searchParams.get("page");
        const limit = searchParams.get("limit");

        const result = await convexQuery("support/queries:getTicketsStaff", {
          status: status || undefined,
          priority: priority || undefined,
          category: category || undefined,
          search: search || undefined,
          page: page ? parseInt(page, 10) : undefined,
          limit: limit ? parseInt(limit, 10) : undefined,
        });

        if (result !== null) {
          return NextResponse.json(result);
        }
      }
    } catch (convexErr) {
      console.error(
        "Convex support tickets fetch failed, falling back to Prisma:",
        convexErr,
      );
    }

    // --- Prisma fallback path ---
    // Get metrics
    if (action === "metrics") {
      const metrics = await getTicketMetrics();
      return NextResponse.json(metrics);
    }

    // Get paginated tickets
    const filters: TicketFilters = {};

    const status = searchParams.get("status");
    if (status) filters.status = status as TicketStatus;

    const priority = searchParams.get("priority");
    if (priority) filters.priority = priority as TicketPriority;

    const category = searchParams.get("category");
    if (category) filters.category = category as TicketCategory;

    const search = searchParams.get("search");
    if (search) filters.search = search;

    const page = searchParams.get("page");
    if (page) filters.page = parseInt(page, 10);

    const limit = searchParams.get("limit");
    if (limit) filters.limit = parseInt(limit, 10);

    const result = await getTickets(filters);
    return NextResponse.json(result);
  } catch (error) {
    console.error("Failed to fetch support tickets:", error);
    return NextResponse.json(
      { error: "Failed to fetch support tickets" },
      { status: 500 },
    );
  }
}
