/**
 * Vendor-attributed SLA (2026-06-02) — monthly vendor SLA report.
 *
 *   GET /api/vendors/[id]/report?windowDays=30&format=html|json
 *
 * format=html (default) returns the rendered HTML report; format=json returns
 * the computed summary so the /vendors page can render a PDF client-side with
 * jspdf (the same path /reports uses). Read access to any authenticated user.
 */
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { computeVendorSla } from '@/lib/services/sla/vendor-sla.service';
import { buildVendorSlaReport } from '@/lib/services/sla/vendor-report';

export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
        return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { id } = await params;
    const vendorId = parseInt(id, 10);
    if (!Number.isFinite(vendorId) || vendorId <= 0) {
        return NextResponse.json({ error: 'Invalid vendor id' }, { status: 400 });
    }

    const vendor = await prisma.vendor.findFirst({ where: { id: vendorId, deletedAt: null }, select: { id: true } });
    if (!vendor) {
        return NextResponse.json({ error: 'Vendor not found' }, { status: 404 });
    }

    const sp = new URL(req.url).searchParams;
    const days = parseInt(sp.get('windowDays') || '30', 10);
    const windowMinutes = (Number.isFinite(days) && days > 0 ? Math.min(days, 365) : 30) * 24 * 60;
    const format = sp.get('format') || 'html';

    const summary = await computeVendorSla(vendorId, windowMinutes);

    if (format === 'json') {
        return NextResponse.json({ success: true, summary });
    }

    const report = buildVendorSlaReport(summary);
    return new NextResponse(report.html, {
        status: 200,
        headers: { 'Content-Type': 'text/html; charset=utf-8' },
    });
}
