import { NextRequest, NextResponse } from 'next/server';
import { getAuvikClient } from '@/lib/services/auvik-factory';
import { AuvikDevice } from '@/lib/types/auvik';

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const companyId = searchParams.get('companyId');
    const companyName = searchParams.get('companyName');

    console.log('Auvik devices API called with:', { companyId, companyName });

    const client = getAuvikClient();
    let devices: AuvikDevice[] = [];
    let tenantId: string | undefined;
    let tenantName: string | undefined;

    // If company name provided, try to find matching tenant
    if (companyName) {
      const tenant = await client.findTenantByName(companyName);
      
      if (tenant) {
        console.log(`Matched company "${companyName}" to Auvik tenant: ${tenant.domainPrefix} (${tenant.id})`);
        tenantId = tenant.id;
        tenantName = tenant.domainPrefix;
        devices = await client.getDevicesByTenant(tenant.id);
      } else {
        console.log(`No Auvik tenant match found for company: ${companyName}`);
        // Return empty array if no tenant match
        devices = [];
      }
    } else {
      // No company filter - fetch all devices
      console.log('Fetching all Auvik devices (no company filter)');
      devices = await client.getAllDevices();
    }

    console.log(`Returning ${devices.length} Auvik devices`);

    return NextResponse.json({
      devices,
      metadata: {
        tenantId,
        tenantName,
        count: devices.length,
      },
    });
  } catch (error) {
    console.error('Error fetching Auvik devices:', error);
    
    // Return empty array instead of error to allow graceful degradation
    return NextResponse.json({
      devices: [],
      metadata: {
        error: error instanceof Error ? error.message : 'Unknown error',
        count: 0,
      },
    });
  }
}
