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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ companyId: string }> }
) {
  try {
    const { companyId } = await params;
    const companyIdInt = parseInt(companyId);

    // Get backup server jobs
    const serverJobs = await postgresClient.query(`
      SELECT bj.*, 'server' as job_source
      FROM veeam_backup_jobs bj
      JOIN veeam_organizations vo ON vo.instance_uid = bj.organization_uid
      WHERE vo.company_id = $1
      ORDER BY bj.last_run DESC NULLS LAST
    `, [companyIdInt]);

    // Get backup agent jobs
    const agentJobs = await postgresClient.query(`
      SELECT aj.*, 'agent' as job_source
      FROM veeam_backup_agent_jobs aj
      JOIN veeam_organizations vo ON vo.instance_uid = aj.organization_uid
      WHERE vo.company_id = $1
      ORDER BY aj.last_run DESC NULLS LAST
    `, [companyIdInt]);

    return NextResponse.json({
      serverJobs: serverJobs.rows,
      agentJobs: agentJobs.rows,
    });
  } catch (error) {
    console.error('[VEEAM-API] company jobs error:', error);
    return NextResponse.json({ serverJobs: [], agentJobs: [] });
  }
}
