import { NextRequest, NextResponse } from 'next/server';
import { getDattoRMMClient } from '@/lib/services/datto-rmm-factory';

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const deviceId = searchParams.get('deviceId');
    
    if (!deviceId) {
      return NextResponse.json({ 
        error: 'Device ID is required' 
      }, { status: 400 });
    }
    
    const rmmClient = getDattoRMMClient();
    
    // Get device with audit data
    const deviceWithAudit = await rmmClient.getDeviceWithAudit(deviceId);
    
    if (!deviceWithAudit) {
      return NextResponse.json({ 
        error: 'Device not found or audit data unavailable' 
      }, { status: 404 });
    }
    
    // Also fetch raw audit data for debugging
    const auditData = await rmmClient.getDeviceAudit(deviceId);
    
    return NextResponse.json({
      device: deviceWithAudit,
      auditData: auditData,
      enhanced: {
        manufacturer: deviceWithAudit.manufacturer,
        model: deviceWithAudit.model,
        serialNumber: deviceWithAudit.serialNumber,
        cpuName: deviceWithAudit.cpuName,
        cpuCores: deviceWithAudit.cpuCores,
        memory: deviceWithAudit.memory,
        diskSize: deviceWithAudit.diskSize
      }
    });
  } catch (error) {
    console.error('Error fetching device audit:', error);
    return NextResponse.json(
      { error: 'Failed to fetch device audit data' },
      { status: 500 }
    );
  }
}
