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 billing items (line items) for this invoice
    const lineItems = await client.queryEntity('BillingItems', {
      filter: [
        { op: 'eq', field: 'invoiceID', value: parseInt(id) }
      ],
    });

    // Sort by item date
    lineItems.sort((a: any, b: any) => {
      const dateA = new Date(a.itemDate || 0).getTime();
      const dateB = new Date(b.itemDate || 0).getTime();
      return dateB - dateA;
    });

    return NextResponse.json({
      lineItems,
    });
  } catch (error) {
    console.error('Error fetching invoice line items:', error);
    return NextResponse.json(
      { error: 'Failed to fetch invoice line items' },
      { status: 500 }
    );
  }
}
