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

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const limit  = Math.min(parseInt(searchParams.get('limit')  ?? '100'), 500);
    const offset = parseInt(searchParams.get('offset') ?? '0');
    const job    = searchParams.get('job');      // filter by job_instance_uid
    const host   = searchParams.get('hostname'); // filter by rmm_hostname

    const conditions: string[] = [];
    const params: any[]        = [];

    if (job) {
      params.push(job);
      conditions.push(`job_instance_uid = $${params.length}`);
    }
    if (host) {
      params.push(host.toLowerCase());
      conditions.push(`LOWER(rmm_hostname) = $${params.length}`);
    }

    const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';

    const [rows, countRes] = await Promise.all([
      postgresClient.query(`
        SELECT
          id, job_instance_uid, job_name, org_name,
          rmm_hostname, rmm_site_name, device_type_category,
          rmm_last_seen, hours_offline, backup_interval_hours, checked_at
        FROM veeam_rpo_offline_log
        ${where}
        ORDER BY checked_at DESC
        LIMIT $${params.length + 1} OFFSET $${params.length + 2}
      `, [...params, limit, offset]),
      postgresClient.query(`SELECT COUNT(*) FROM veeam_rpo_offline_log ${where}`, params),
    ]);

    return NextResponse.json({
      total:  parseInt(countRes.rows[0].count),
      limit,
      offset,
      rows:   rows.rows,
    });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
