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

export async function GET(request: NextRequest) {
  try {
    // Check if API is configured
    if (!process.env.AUTOTASK_API_URL || 
        !process.env.AUTOTASK_USERNAME || 
        !process.env.AUTOTASK_SECRET || 
        !process.env.AUTOTASK_API_INTEGRATION_CODE) {
      return NextResponse.json(
        { 
          error: 'Autotask API not configured',
          message: 'Please set up your environment variables.'
        },
        { status: 503 }
      );
    }

    const client = getAutotaskClient();
    const searchParams = request.nextUrl.searchParams;
    const companyId = searchParams.get('companyId');

    if (!companyId) {
      // Return empty array if no company selected
      return NextResponse.json({ 
        configurationItems: [],
        message: 'Please select a company to view configuration items'
      });
    }

    const configurationItems = await client.getConfigurationItemsByCompany(parseInt(companyId));
    
    // Sort by reference title for better display
    configurationItems.sort((a, b) => 
      (a.referenceTitle || '').localeCompare(b.referenceTitle || '')
    );

    return NextResponse.json({ 
      configurationItems,
      count: configurationItems.length,
      companyId: parseInt(companyId)
    });
  } catch (error) {
    console.error('Error fetching configuration items:', error);
    
    if (error instanceof Error) {
      return NextResponse.json(
        { 
          error: 'Failed to fetch configuration items',
          message: error.message,
        },
        { status: 500 }
      );
    }
    
    return NextResponse.json(
      { error: 'An unexpected error occurred while fetching configuration items' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const client = getAutotaskClient();
    const body = await request.json();
    
    const configurationItem = await client.createConfigurationItem(body);
    
    return NextResponse.json({ configurationItem });
  } catch (error) {
    console.error('Error creating configuration item:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to create configuration item' },
      { status: 500 }
    );
  }
}
