/**
 * Staff Support Ticket Detail API
 * GET /api/staff/dashboard/support/[id] - Get ticket detail (staff view)
 * PUT /api/staff/dashboard/support/[id] - Update ticket status/priority
 *
 * Convex-first with Prisma fallback.
 */

import { NextRequest, NextResponse } from "next/server";
import { validateStaffSession } from "@/lib/staff-session";
import {
  getTicketById,
  updateTicketStatus,
  updateTicketPriority,
  resolveTicket,
  type TicketStatus,
  type TicketPriority,
} from "@/lib/services/support-tickets.service";
import { convexQuery, convexMutation } from "@/lib/convex-client";

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

    const { id } = await params;

    // --- Convex-first path ---
    try {
      const ticketResult = (await convexQuery(
        "support/queries:getTicketWithMessages",
        { ticketId: id },
      )) as Record<string, unknown> | null;

      if (ticketResult) {
        const ticket = {
          id: ticketResult._id ?? ticketResult.id,
          userId: ticketResult.userId,
          subject: ticketResult.subject,
          message: ticketResult.message,
          category: ticketResult.category,
          priority: ticketResult.priority,
          status: ticketResult.status,
          attachments: ticketResult.attachments,
          resolvedAt: ticketResult.resolvedAt
            ? new Date(ticketResult.resolvedAt as number).toISOString()
            : null,
          resolvedBy: ticketResult.resolvedBy,
          resolution: ticketResult.resolution,
          createdAt: ticketResult.createdAt
            ? new Date(ticketResult.createdAt as number).toISOString()
            : null,
          updatedAt: ticketResult.updatedAt
            ? new Date(ticketResult.updatedAt as number).toISOString()
            : null,
        };

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

    // --- Prisma fallback ---
    const ticket = await getTicketById(id);

    if (!ticket) {
      return NextResponse.json({ error: "Ticket not found" }, { status: 404 });
    }

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

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const session = await validateStaffSession(request);
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Only ADMIN and SUPER_ADMIN can update tickets
    if (session.role !== "ADMIN" && session.role !== "SUPER_ADMIN") {
      return NextResponse.json(
        { error: "Insufficient permissions" },
        { status: 403 },
      );
    }

    const { id } = await params;
    const body = await request.json();

    // --- Convex-first path ---
    try {
      if (body.status) {
        await convexMutation("support/mutations:updateStatus", {
          id: id as unknown,
          status: body.status,
          resolvedBy: session.id,
          resolution: body.resolution || undefined,
        });
      } else if (body.priority) {
        await convexMutation("support/mutations:updateTicket", {
          id: id as unknown,
          priority: body.priority,
        });
      } else if (body.resolution) {
        await convexMutation("support/mutations:updateStatus", {
          id: id as unknown,
          status: "RESOLVED",
          resolvedBy: session.id,
          resolution: body.resolution,
        });
      } else {
        return NextResponse.json(
          { error: "No valid update provided" },
          { status: 400 },
        );
      }

      // Fetch updated ticket from Convex
      const updated = (await convexQuery(
        "support/queries:getTicketWithMessages",
        { ticketId: id },
      )) as Record<string, unknown> | null;

      if (updated) {
        return NextResponse.json({
          ticket: {
            id: updated._id ?? updated.id,
            userId: updated.userId,
            subject: updated.subject,
            category: updated.category,
            priority: updated.priority,
            status: updated.status,
            resolvedAt: updated.resolvedAt
              ? new Date(updated.resolvedAt as number).toISOString()
              : null,
            resolvedBy: updated.resolvedBy,
            resolution: updated.resolution,
            createdAt: updated.createdAt
              ? new Date(updated.createdAt as number).toISOString()
              : null,
            updatedAt: updated.updatedAt
              ? new Date(updated.updatedAt as number).toISOString()
              : null,
          },
        });
      }
    } catch (convexErr) {
      console.error(
        "Convex ticket update failed, falling back to Prisma:",
        convexErr,
      );
    }

    // --- Prisma fallback ---
    let ticket;

    if (body.status) {
      ticket = await updateTicketStatus(
        id,
        body.status as TicketStatus,
        session.id,
        body.resolution,
      );
    } else if (body.priority) {
      ticket = await updateTicketPriority(id, body.priority as TicketPriority);
    } else if (body.resolution) {
      ticket = await resolveTicket(id, session.id, body.resolution);
    } else {
      return NextResponse.json(
        { error: "No valid update provided" },
        { status: 400 },
      );
    }

    if (!ticket) {
      return NextResponse.json({ error: "Ticket not found" }, { status: 404 });
    }

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