import { NextRequest, NextResponse } from 'next/server';
import { postgresClient } from '@/lib/services/postgres-client';
import { getAutotaskClient } from '@/lib/services/autotask-factory';

let _statusPicklist: Record<number, string> | null = null;
let _priorityPicklist: Record<number, string> | null = null;

async function getPicklists() {
  const client = getAutotaskClient();
  if (!_statusPicklist) {
    try { _statusPicklist = await client.getTicketStatusPicklist(); } catch { _statusPicklist = {}; }
  }
  if (!_priorityPicklist) {
    try { _priorityPicklist = await client.getTicketPriorityPicklist(); } catch { _priorityPicklist = {}; }
  }
  return { statusPicklist: _statusPicklist!, priorityPicklist: _priorityPicklist! };
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ ticketNumber: string }> }
) {
  try {
    const { ticketNumber } = await params;

    const [result, { statusPicklist, priorityPicklist }] = await Promise.all([
      postgresClient.query(
        `SELECT t.*,
                r.first_name || ' ' || r.last_name AS assigned_resource_name
         FROM tickets t
         LEFT JOIN resources r ON r.id = t.assigned_resource_id
         WHERE t.ticket_number = $1
           AND t.is_deleted = false
         LIMIT 1`,
        [ticketNumber]
      ),
      getPicklists(),
    ]);

    if (result.rows.length === 0) {
      return NextResponse.json({ error: 'Ticket not found' }, { status: 404 });
    }

    const row = result.rows[0];

    const ticket = {
      id: Number(row.id),
      ticketNumber: row.ticket_number,
      title: row.title,
      description: row.description,
      resolution: row.resolution,
      status: row.status,
      priority: row.priority,
      statusLabel: statusPicklist[row.status] ?? null,
      priorityLabel: priorityPicklist[row.priority] ?? null,
      assignedResourceName: row.assigned_resource_name ?? null,
      createDate: row.create_date,
      dueDateTime: row.due_date_time,
      resolvedDateTime: row.resolved_date_time,
      purchaseOrderNumber: row.purchase_order_number ?? null,
    };

    return NextResponse.json({ ticket });
  } catch (error) {
    console.error('Error fetching ticket by number:', error);
    return NextResponse.json({ error: 'Failed to fetch ticket' }, { status: 500 });
  }
}
