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

export async function GET() {
  try {
    const [alarms, summary] = await Promise.all([
      postgresClient.query(`
        SELECT a.instance_uid, a.object_type, a.object_name, a.object_computer_name,
          a.last_activation_status, a.last_activation_time, a.last_activation_message,
          a.last_activation_remark, a.repeat_count, a.area, a.resolved, a.synced_at,
          o.name as organization_name
        FROM veeam_alarms a
        LEFT JOIN veeam_organizations o ON o.instance_uid = a.organization_uid
        ORDER BY a.last_activation_time DESC NULLS LAST
        LIMIT 500
      `),
      postgresClient.query(`
        SELECT
          COUNT(*) as total,
          COUNT(*) FILTER (WHERE resolved = false) as active,
          COUNT(*) FILTER (WHERE resolved = true) as resolved,
          COUNT(*) FILTER (WHERE last_activation_status = 'Resolved') as status_resolved,
          COUNT(*) FILTER (WHERE last_activation_status = 'Active') as status_active,
          COUNT(*) FILTER (WHERE last_activation_status = 'Warning') as status_warning,
          MAX(synced_at) as last_sync
        FROM veeam_alarms
      `),
    ]);

    const s = summary.rows[0];
    return NextResponse.json({
      alarms: alarms.rows,
      summary: {
        total: parseInt(s.total),
        active: parseInt(s.active),
        resolved: parseInt(s.resolved),
        statusResolved: parseInt(s.status_resolved),
        statusActive: parseInt(s.status_active),
        statusWarning: parseInt(s.status_warning),
        lastSync: s.last_sync,
      },
    });
  } catch (error) {
    console.error('[VEEAM-ALARMS-API]', error);
    return NextResponse.json({ error: 'Failed to fetch alarms' }, { status: 500 });
  }
}
