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

export async function GET() {
  const [analyzedRes, eligibleRes] = await Promise.all([
    postgresClient.query(`
      SELECT COUNT(*) AS total_analyzed, MAX(analyzed_at) AS last_analyzed_at
      FROM veeam_ticket_analysis
      WHERE ticket_created_at >= DATE_TRUNC('year', NOW())
    `),
    postgresClient.query(`
      SELECT COUNT(DISTINCT t.id) AS total_eligible
      FROM tickets t
      INNER JOIN time_entries te ON te.ticket_id = t.id
      WHERE t.title ILIKE 'Veeam:%'
        AND t.title NOT ILIKE '[Veeam RPO]%'
        AND t.create_date >= DATE_TRUNC('year', NOW())
    `),
  ]);

  return NextResponse.json({
    is_running:      analysisState.isRunning,
    run_total:       analysisState.total,
    run_done:        analysisState.done,
    run_errors:      analysisState.errors,
    run_started_at:  analysisState.startedAt,
    total_analyzed:  parseInt(analyzedRes.rows[0]?.total_analyzed ?? 0),
    total_eligible:  parseInt(eligibleRes.rows[0]?.total_eligible ?? 0),
    last_analyzed_at: analyzedRes.rows[0]?.last_analyzed_at ?? null,
  });
}
