import { NextRequest, NextResponse } from 'next/server';
import { getVeeamRpoService } from '@/lib/services/veeam-rpo-service';

export async function GET() {
  try {
    const svc = getVeeamRpoService();
    const status = await svc.getStatus();
    return NextResponse.json(status);
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json().catch(() => ({}));
    const dryRun = body.dryRun === true;

    if (dryRun) {
      const svc = getVeeamRpoService();
      const status = await svc.getStatus();
      const MAX_AGE = 720;
      const wouldCreate = status.jobs.filter(j =>
        j.is_breached && !j.open_ticket && (j.hours_since_backup ?? 0) <= MAX_AGE
      ).length;
      const wouldSkipTooOld = status.jobs.filter(j =>
        j.is_breached && !j.open_ticket && (j.hours_since_backup ?? 0) > MAX_AGE
      ).length;
      const wouldResolve = status.jobs.filter(j => !j.is_breached && j.open_ticket).length;
      const wouldEscalate = status.jobs.filter(j => {
        if (!j.is_breached || !j.open_ticket) return false;
        const hours = j.hours_since_backup ?? 0;
        const target = hours >= 168 ? 'critical' : hours >= 72 ? 'high' : 'medium';
        const rank: Record<string, number> = { medium: 1, high: 2, critical: 3 };
        return (rank[target] ?? 0) > (rank[j.open_ticket.priority_level] ?? 0);
      }).length;
      return NextResponse.json({ dryRun: true, wouldCreate, wouldResolve, wouldEscalate, wouldSkipTooOld, ...status });
    }

    const svc = getVeeamRpoService();
    const result = await svc.runCheck();
    return NextResponse.json(result);
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
