/**
 * Support Ticket Detail API - User-facing
 *
 * GET /api/support/tickets/[id] - Get ticket with message thread
 *
 * All data access goes through Convex. No Prisma fallback.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { logger } from "@/lib/logger";
import { convexQueryStrict } from "@/lib/convex-client";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

/**
 * GET /api/support/tickets/[id]
 * Get a ticket with its full message thread
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = await params;

    // convexQueryStrict throws on Convex errors (caught below as 500)
    // and returns null only when the ticket genuinely doesn't exist
    const result = await convexQueryStrict("support/queries:getTicketWithMessages", {
      ticketId: id,
    });

    if (result === null || result === undefined) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const ticket = result as any;
    // Verify user owns the ticket
    if (ticket.userId !== user.userId) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }
    // Extract messages from messageThread for client compatibility
    const messages = (ticket.messageThread ?? []).map((m: Record<string, unknown>) => ({
      id: m._id ?? m.id,
      ticketId: m.ticketId,
      senderId: m.senderId,
      senderType: m.senderType,
      message: m.message,
      createdAt: m.createdAt ? new Date(m.createdAt as number).toISOString() : null,
    }));
    // Map Convex _id to id for client compatibility
    const ticketResponse = {
      ...ticket,
      id: ticket._id ?? ticket.id,
      createdAt: ticket.createdAt ? new Date(ticket.createdAt as number).toISOString() : null,
      updatedAt: ticket.updatedAt ? new Date(ticket.updatedAt as number).toISOString() : null,
    };
    return NextResponse.json({ ticket: ticketResponse, messages, success: true });
  } catch (error) {
    logger.error("Failed to fetch ticket", { error });
    return NextResponse.json(
      { error: "Failed to fetch ticket" },
      { status: 500 },
    );
  }
}
