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

interface AuvikConfigurationResponse {
  data: Array<{
    type: string;
    id: string;
    attributes: {
      deviceId: string;
      backupDate: string;
      configType: string;
      configText?: string;
      configSize?: number;
    };
  }>;
  links?: {
    next?: string;
  };
}

/**
 * GET /api/auvik/device-config?hostname=YNGHYNSWP19
 * Fetch device configuration from Auvik API
 */
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const hostname = searchParams.get('hostname');
    const deviceId = searchParams.get('deviceId');

    if (!hostname && !deviceId) {
      return NextResponse.json(
        { error: 'Either hostname or deviceId parameter is required' },
        { status: 400 }
      );
    }

    // Get Auvik client
    const client = getAuvikClient();
    const config = {
      apiUrl: process.env.AUVIK_API_URL || 'https://auvikapi.us1.my.auvik.com',
      apiUser: process.env.AUVIK_API_USER || '',
      apiKey: process.env.AUVIK_API_KEY || '',
    };

    let targetDeviceId = deviceId;

    // If hostname provided, find the device first
    if (hostname && !deviceId) {
      console.log(`Searching for device with hostname: ${hostname}`);
      const devices = await client.getAllDevices();
      
      const matchingDevice = devices.find(
        (d: AuvikDevice) => d.deviceName.toLowerCase() === hostname.toLowerCase()
      );

      if (!matchingDevice) {
        return NextResponse.json(
          { 
            error: `Device not found with hostname: ${hostname}`,
            availableDevices: devices.map((d: AuvikDevice) => ({
              name: d.deviceName,
              id: d.id,
              type: d.deviceType,
            })).slice(0, 20), // Return first 20 for reference
          },
          { status: 404 }
        );
      }

      targetDeviceId = matchingDevice.id;
      console.log(`Found device: ${matchingDevice.deviceName} (ID: ${targetDeviceId})`);
    }

    // Fetch device configuration
    console.log(`Fetching configuration for device ID: ${targetDeviceId}`);
    const configUrl = `${config.apiUrl}/v1/inventory/device/configuration?filter[deviceId]=${targetDeviceId}`;
    
    const credentials = Buffer.from(`${config.apiUser}:${config.apiKey}`).toString('base64');
    
    const response = await fetch(configUrl, {
      headers: {
        Authorization: `Basic ${credentials}`,
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error(`Auvik API error: ${response.status} ${response.statusText}`, errorText);
      
      // Try device detail endpoint as fallback
      const detailUrl = `${config.apiUrl}/v1/inventory/device/detail/${targetDeviceId}`;
      const detailResponse = await fetch(detailUrl, {
        headers: {
          Authorization: `Basic ${credentials}`,
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      });
      
      if (detailResponse.ok) {
        const detailData = await detailResponse.json();
        return NextResponse.json({
          message: 'Configuration endpoint not available, returning device details',
          deviceId: targetDeviceId,
          deviceDetail: detailData,
        });
      }
      
      return NextResponse.json(
        { 
          error: `Failed to fetch configuration: ${response.status} ${response.statusText}`,
          details: errorText,
        },
        { status: response.status }
      );
    }

    const configData: AuvikConfigurationResponse = await response.json();
    
    console.log(`Found ${configData.data.length} configuration(s) for device ${targetDeviceId}`);
    
    // Return the configuration data
    return NextResponse.json({
      deviceId: targetDeviceId,
      hostname: hostname,
      configurations: configData.data.map(config => ({
        type: config.attributes.configType,
        backupDate: config.attributes.backupDate,
        size: config.attributes.configSize,
        configText: config.attributes.configText,
      })),
      rawResponse: configData,
    });

  } catch (error) {
    console.error('Error fetching device configuration:', error);
    return NextResponse.json(
      { 
        error: 'Internal server error',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}
