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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const client = getAutotaskClient();
    
    // Get tickets related to this configuration item
    const tickets = await client.queryEntity('Tickets', {
      filter: [
        { op: 'eq', field: 'configurationItemID', value: parseInt(id) }
      ],
    });

    // Fetch picklist values for status and priority
    let statusPicklist: Record<string | number, string> = {};
    let priorityPicklist: Record<string | number, string> = {};
    
    try {
      const [statusResponse, priorityResponse] = await Promise.all([
        client.getPicklistValues('Tickets', 'status'),
        client.getPicklistValues('Tickets', 'priority')
      ]);
      statusPicklist = statusResponse;
      priorityPicklist = priorityResponse;
      console.log('Status picklist:', statusPicklist);
      console.log('Priority picklist:', priorityPicklist);
    } catch (err) {
      console.error('Error fetching picklists:', err);
    }

    // Enrich with resource names and picklist labels
    const enrichedTickets = await Promise.all(
      tickets.map(async (ticket: any) => {
        let assignedResourceName = null;
        if (ticket.assignedResourceID) {
          try {
            const resource = await client.getEntityById('Resources', ticket.assignedResourceID) as any;
            assignedResourceName = resource ? `${resource.firstName} ${resource.lastName}` : null;
          } catch (err) {
            console.error('Error fetching resource:', err);
          }
        }
        
        // Get status and priority labels from picklist object
        console.log('Ticket status value:', ticket.status, 'Label:', statusPicklist[ticket.status]);
        console.log('Ticket priority value:', ticket.priority, 'Label:', priorityPicklist[ticket.priority]);
        const statusLabel = statusPicklist[ticket.status] || ticket.status;
        const priorityLabel = priorityPicklist[ticket.priority] || ticket.priority;
        
        return {
          ...ticket,
          assignedResourceName,
          status: statusLabel,
          priority: priorityLabel,
        };
      })
    );

    // Sort by created date (most recent first)
    enrichedTickets.sort((a: any, b: any) => {
      const dateA = new Date(a.createDate || 0).getTime();
      const dateB = new Date(b.createDate || 0).getTime();
      return dateB - dateA;
    });

    return NextResponse.json({
      tickets: enrichedTickets,
    });
  } catch (error) {
    console.error('Error fetching related tickets:', error);
    return NextResponse.json(
      { error: 'Failed to fetch related tickets' },
      { status: 500 }
    );
  }
}
