import { NextRequest, NextResponse } from 'next/server';
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<{ id: string }> }
) {
  try {
    const { id } = await params;
    const client = getAutotaskClient();
    
    const [ticket, { statusPicklist, priorityPicklist }] = await Promise.all([
      client.getEntityById('Tickets', parseInt(id)),
      getPicklists(),
    ]);
    
    if (!ticket) {
      return NextResponse.json(
        { error: 'Ticket not found' },
        { status: 404 }
      );
    }

    const ticketData = ticket as any;

    let assignedResourceName = null;
    if (ticketData.assignedResourceID) {
      try {
        const resource = await client.getEntityById('Resources', ticketData.assignedResourceID) as any;
        assignedResourceName = resource ? `${resource.firstName} ${resource.lastName}` : null;
      } catch (err) {
        console.error('Error fetching resource:', err);
      }
    }

    return NextResponse.json({
      ticket: {
        ...ticket,
        assignedResourceName,
        statusLabel: statusPicklist[ticketData.status] ?? null,
        priorityLabel: priorityPicklist[ticketData.priority] ?? null,
      },
    });
  } catch (error) {
    console.error('Error fetching ticket:', error);
    return NextResponse.json(
      { error: 'Failed to fetch ticket' },
      { status: 500 }
    );
  }
}
