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

export async function GET() {
  try {
    const result = await postgresClient.query(`
      SELECT
        vo.instance_uid as organization_uid,
        vo.company_id,
        COALESCE(c.company_name, vo.name) as company_name,
        vo.name as organization_name,
        (SELECT COUNT(*) FROM veeam_protected_workloads pw WHERE pw.organization_uid = vo.instance_uid) as protected_workload_count,
        (SELECT COUNT(*) FROM veeam_backup_jobs bj WHERE bj.organization_uid = vo.instance_uid AND bj.is_enabled = true) as backup_server_job_count,
        (SELECT COUNT(*) FROM veeam_backup_agent_jobs aj WHERE aj.organization_uid = vo.instance_uid AND aj.is_enabled = true) as backup_agent_job_count,
        (SELECT COUNT(*) FROM veeam_backup_jobs bj WHERE bj.organization_uid = vo.instance_uid AND bj.status = 'Failed' AND bj.is_enabled = true) as failed_server_jobs,
        (SELECT COUNT(*) FROM veeam_backup_agent_jobs aj WHERE aj.organization_uid = vo.instance_uid AND aj.status = 'Failed' AND aj.is_enabled = true) as failed_agent_jobs,
        (SELECT COUNT(*) FROM veeam_backup_jobs bj WHERE bj.organization_uid = vo.instance_uid AND bj.status = 'Warning' AND bj.is_enabled = true) as warning_server_jobs,
        (SELECT COUNT(*) FROM veeam_backup_agent_jobs aj WHERE aj.organization_uid = vo.instance_uid AND aj.status = 'Warning' AND aj.is_enabled = true) as warning_agent_jobs,
        (SELECT MAX(pw.latest_restore_point_date) FROM veeam_protected_workloads pw WHERE pw.organization_uid = vo.instance_uid) as last_successful_backup,
        (SELECT MIN(pw.latest_restore_point_date) FROM veeam_protected_workloads pw WHERE pw.organization_uid = vo.instance_uid) as oldest_restore_point
      FROM veeam_organizations vo
      LEFT JOIN companies c ON c.id = vo.company_id
      WHERE vo.type = 'Company'
      ORDER BY COALESCE(c.company_name, vo.name)
    `);

    const companies = result.rows.map((row: any) => {
      const failedJobs = parseInt(row.failed_server_jobs) + parseInt(row.failed_agent_jobs);
      const warningJobs = parseInt(row.warning_server_jobs) + parseInt(row.warning_agent_jobs);
      let lastJobStatus = 'Success';
      if (failedJobs > 0) lastJobStatus = 'Failed';
      else if (warningJobs > 0) lastJobStatus = 'Warning';

      return {
        organizationUid: row.organization_uid,
        companyId: row.company_id,
        companyName: row.company_name,
        organizationName: row.organization_name,
        protectedWorkloadCount: parseInt(row.protected_workload_count),
        backupServerJobCount: parseInt(row.backup_server_job_count),
        backupAgentJobCount: parseInt(row.backup_agent_job_count),
        failedJobCount: failedJobs,
        warningJobCount: warningJobs,
        lastJobStatus,
        lastSuccessfulBackup: row.last_successful_backup,
        oldestRestorePoint: row.oldest_restore_point,
      };
    });

    return NextResponse.json(companies);
  } catch (error) {
    console.error('[VEEAM-API] companies error:', error);
    return NextResponse.json([]);
  }
}
