/**
 * Vendor-attributed SLA (2026-06-02) — monthly vendor SLA report (HTML).
 *
 * Reuses the report-builder.ts shape (inline-styled HTML table suitable for
 * email) to produce a per-vendor monthly summary: promised vs measured uptime,
 * attainment, error-budget remaining, breaches, MTTR, downtime-by-layer, and
 * the estimated service credit. The matching PDF is produced client-side with
 * jspdf + jspdf-autotable (already deps) on the /vendors detail download button,
 * mirroring how /reports renders PDFs.
 */
import type { VendorSlaSummary } from './vendor-sla.service';
import { VENDOR_LAYERS } from './error-class-layer';

export interface BuiltVendorReport {
    subject: string;
    html: string;
}

function escapeHtml(s: string): string {
    return s
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

function uptimeColour(meeting: boolean): string {
    return meeting ? '#10b981' : '#ef4444';
}

export function buildVendorSlaReport(summary: VendorSlaSummary, now: Date = new Date()): BuiltVendorReport {
    const subject = `Vendor SLA — ${summary.name} — last ${summary.windowDays}d`;

    const monitorRows = summary.monitors
        .map((m) => {
            const colour = uptimeColour(m.slo.meetingSla);
            return `<tr>
                <td style="padding:6px 12px;">${escapeHtml(m.name)}</td>
                <td style="padding:6px 12px;text-align:right;color:${colour};font-weight:bold;">${m.slo.sli.toFixed(2)}%</td>
                <td style="padding:6px 12px;text-align:right;color:#64748b;">${m.slo.errorBudget.remainingPercent.toFixed(0)}%</td>
                <td style="padding:6px 12px;text-align:right;color:#64748b;">${m.breaches}</td>
                <td style="padding:6px 12px;text-align:right;color:#64748b;">${m.mttrMinutes.toFixed(0)}m</td>
            </tr>`;
        })
        .join('');

    const layerRows = VENDOR_LAYERS.map((layer) => {
        const pct = summary.attribution.percentByLayer[layer];
        if (pct <= 0) return '';
        return `<tr>
            <td style="padding:4px 12px;">${layer}</td>
            <td style="padding:4px 12px;text-align:right;color:#64748b;">${pct.toFixed(1)}%</td>
        </tr>`;
    }).join('');

    const credit = summary.creditPercentEstimate === null
        ? '—'
        : `${summary.creditPercentEstimate}% of spend`;

    const headline = uptimeColour(summary.meetingSla);

    const html = `
    <div style="font-family:system-ui,sans-serif;color:#0f172a;max-width:680px;margin:0 auto;">
        <h2 style="margin:0 0 4px 0;">Vendor SLA report — ${escapeHtml(summary.name)}</h2>
        <p style="color:#64748b;margin:0 0 16px 0;font-size:13px;">
            Window: last ${summary.windowDays} days &middot;
            generated ${now.toISOString().slice(0, 10)}
        </p>

        <table style="width:100%;border-collapse:collapse;font-size:13px;background:#fff;border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;margin-bottom:16px;">
            <tbody>
                <tr><td style="padding:6px 12px;color:#64748b;">Promised uptime</td><td style="padding:6px 12px;text-align:right;font-weight:bold;">${summary.promisedUptime.toFixed(2)}%</td></tr>
                <tr><td style="padding:6px 12px;color:#64748b;">Measured uptime</td><td style="padding:6px 12px;text-align:right;font-weight:bold;color:${headline};">${summary.measuredUptime.toFixed(2)}%</td></tr>
                <tr><td style="padding:6px 12px;color:#64748b;">Attainment</td><td style="padding:6px 12px;text-align:right;">${summary.attainment >= 0 ? '+' : ''}${summary.attainment.toFixed(2)} pts</td></tr>
                <tr><td style="padding:6px 12px;color:#64748b;">Error budget remaining</td><td style="padding:6px 12px;text-align:right;">${summary.errorBudgetRemainingPercent.toFixed(0)}%</td></tr>
                <tr><td style="padding:6px 12px;color:#64748b;">Breaches (outage episodes)</td><td style="padding:6px 12px;text-align:right;">${summary.breaches}</td></tr>
                <tr><td style="padding:6px 12px;color:#64748b;">MTTR</td><td style="padding:6px 12px;text-align:right;">${summary.mttrMinutes.toFixed(0)} min</td></tr>
                <tr><td style="padding:6px 12px;color:#64748b;">Estimated service credit</td><td style="padding:6px 12px;text-align:right;">${credit}</td></tr>
            </tbody>
        </table>

        <h3 style="margin:0 0 8px 0;font-size:14px;">Per-monitor</h3>
        ${summary.monitors.length === 0
            ? '<p style="color:#94a3b8;font-style:italic;">No monitors assigned to this vendor.</p>'
            : `<table style="width:100%;border-collapse:collapse;font-size:13px;background:#fff;border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;margin-bottom:16px;">
                <thead style="background:#f8fafc;text-align:left;color:#64748b;text-transform:uppercase;font-size:11px;font-weight:bold;">
                    <tr>
                        <th style="padding:8px 12px;">Monitor</th>
                        <th style="padding:8px 12px;text-align:right;">Uptime</th>
                        <th style="padding:8px 12px;text-align:right;">Budget left</th>
                        <th style="padding:8px 12px;text-align:right;">Breaches</th>
                        <th style="padding:8px 12px;text-align:right;">MTTR</th>
                    </tr>
                </thead>
                <tbody>${monitorRows}</tbody>
            </table>`
        }

        <h3 style="margin:0 0 8px 0;font-size:14px;">Downtime by vendor layer</h3>
        ${layerRows || '<p style="color:#94a3b8;font-style:italic;">No attributable downtime in the window.</p>'}
        ${summary.attribution.percentUnattributed > 0
            ? `<p style="color:#94a3b8;font-size:12px;margin-top:8px;">Unattributed: ${summary.attribution.percentUnattributed.toFixed(1)}%</p>`
            : ''}
        ${layerRows
            ? `<table style="width:100%;border-collapse:collapse;font-size:13px;background:#fff;border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;">
                <tbody>${layerRows}</tbody>
            </table>`
            : ''}
    </div>
    `;

    return { subject, html };
}
