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

/**
 * Lightweight endpoint that only fetches the PSA configuration item
 * without any RMM or Auvik matching. Used when devices are already known.
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const autotaskClient = getAutotaskClient();
    
    // Fetch only the configuration item
    const autotaskDevice = await autotaskClient.getConfigurationItemById(parseInt(id));
    
    if (!autotaskDevice) {
      return NextResponse.json(
        { error: 'Configuration item not found' },
        { status: 404 }
      );
    }
    
    // Get company name
    let companyName: string | null = null;
    try {
      const company = await autotaskClient.getCompanyById(autotaskDevice.companyID);
      companyName = company?.companyName || null;
    } catch (err) {
      console.error('Failed to fetch company name:', err);
    }
    
    return NextResponse.json({
      autotaskDevice,
      companyName
    });
  } catch (error) {
    console.error('Error fetching configuration item:', error);
    return NextResponse.json(
      { error: 'Failed to fetch configuration item' },
      { status: 500 }
    );
  }
}
