import { NextResponse } from 'next/server';
import postgresClient from '@/lib/services/postgres-client';

export async function GET() {
  try {
    const [agents, summary] = await Promise.all([
      postgresClient.query(`
        SELECT a.instance_uid, a.name, a.agent_platform, a.status, a.management_agent_status,
          a.operation_mode, a.platform, a.version, a.version_status, a.management_mode,
          a.total_jobs_count, a.running_jobs_count, a.success_jobs_count,
          a.activation_time, a.synced_at,
          o.name as organization_name
        FROM veeam_backup_agents a
        LEFT JOIN veeam_organizations o ON o.instance_uid = a.organization_uid
        ORDER BY a.name ASC
      `),
      postgresClient.query(`
        SELECT
          COUNT(*) as total,
          COUNT(*) FILTER (WHERE status = 'Active') as active,
          COUNT(*) FILTER (WHERE status != 'Active') as inactive,
          COUNT(*) FILTER (WHERE management_agent_status = 'Inaccessible') as inaccessible,
          COUNT(*) FILTER (WHERE version_status = 'Outdated') as outdated,
          COUNT(*) FILTER (WHERE agent_platform = 'Windows') as windows,
          COUNT(*) FILTER (WHERE agent_platform = 'Linux') as linux,
          COUNT(*) FILTER (WHERE agent_platform = 'Mac') as mac,
          MAX(synced_at) as last_sync
        FROM veeam_backup_agents
      `),
    ]);

    const s = summary.rows[0];
    return NextResponse.json({
      agents: agents.rows,
      summary: {
        total: parseInt(s.total),
        active: parseInt(s.active),
        inactive: parseInt(s.inactive),
        inaccessible: parseInt(s.inaccessible),
        outdated: parseInt(s.outdated),
        windows: parseInt(s.windows),
        linux: parseInt(s.linux),
        mac: parseInt(s.mac),
        lastSync: s.last_sync,
      },
    });
  } catch (error) {
    console.error('[VEEAM-AGENTS-API]', error);
    return NextResponse.json({ error: 'Failed to fetch agents' }, { status: 500 });
  }
}
