import { NextResponse } from 'next/server';
import { getAddigyClient } from '@/lib/services/addigy-factory';
import { getCachedData, setCachedData } from '@/lib/services/redis-client';

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const policyId = searchParams.get('policyId');
    const online = searchParams.get('online');

    // Create cache key based on query parameters
    const cacheKey = `addigy:devices:${policyId || 'all'}:${online || 'all'}`;
    
    // Try to get cached data
    const cachedDevices = await getCachedData<any[]>(cacheKey);
    if (cachedDevices) {
      console.log(`Cache hit for key: ${cacheKey}`);
      return NextResponse.json({
        success: true,
        data: cachedDevices,
        count: cachedDevices.length,
        cached: true,
      });
    }

    console.log(`Cache miss for key: ${cacheKey}, fetching from API`);
    const addigyClient = getAddigyClient();

    let devices;

    if (policyId) {
      // Get devices by policy
      devices = await addigyClient.getDevicesByPolicy(policyId);
    } else if (online === 'true') {
      // Get only online devices
      devices = await addigyClient.getOnlineDevices();
    } else {
      // Get all devices
      devices = await addigyClient.getAllDevices();
    }

    // Cache the result for 5 minutes
    await setCachedData(cacheKey, devices, 300);

    return NextResponse.json({
      success: true,
      data: devices,
      count: devices.length,
      cached: false,
    });
  } catch (error) {
    console.error('Error fetching Addigy devices:', error);
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    );
  }
}
