/**
 * Brand Health Email Templates
 * ─────────────────────────────
 * Sends degraded/resolved alerts to ALERT_EMAIL_RECIPIENT.
 * Uses the existing sendEmail() nodemailer wrapper.
 */

import { sendEmail } from "./email-sender";
import type { BrandHealthAlert } from "@prisma/client";

const ALERT_RECIPIENT = process.env.ALERT_EMAIL_RECIPIENT ?? "";
const APP_URL = process.env.NEXT_PUBLIC_APP_URL ?? "https://app.meseoapp.com";

function fmt(n: number): string {
  return Math.round(n).toLocaleString();
}

function fmtPct(pct: number): string {
  return `${Math.round(pct * 100)}%`;
}

function hoursAgo(date: Date): string {
  const h = Math.floor((Date.now() - date.getTime()) / 3_600_000);
  return h <= 1 ? "1 hour" : `${h} hours`;
}

// ─── Degraded alert ──────────────────────────────────────────────────────────

export async function sendDegradedAlert(
  brand: { id: string; name: string; domain: string },
  alert: BrandHealthAlert,
) {
  if (!ALERT_RECIPIENT) {
    console.warn("[brand-health-email] ALERT_EMAIL_RECIPIENT not set — skipping degraded alert");
    return;
  }

  const dropPctStr = fmtPct(alert.dropPct);
  const subject = `🚨 [meSEO] ${brand.name} ingest dropped ${dropPctStr}`;

  const html = `
<div style="font-family: monospace; font-size: 14px; color: #1a1a1a; max-width: 640px;">
  <h2 style="color: #dc2626; margin: 0 0 16px;">🚨 Site Tag Ingest Degraded</h2>

  <table style="border-collapse: collapse; width: 100%; margin-bottom: 20px;">
    <tr><td style="padding: 4px 12px 4px 0; color: #6b7280; white-space: nowrap;">Brand</td>
        <td style="padding: 4px 0;"><strong>${brand.name}</strong> (${brand.domain})</td></tr>
    <tr><td style="padding: 4px 12px 4px 0; color: #6b7280;">Status</td>
        <td style="padding: 4px 0; color: #dc2626;"><strong>DEGRADED</strong> — sustained for 2+ hours</td></tr>
    <tr><td style="padding: 4px 12px 4px 0; color: #6b7280;">Started</td>
        <td style="padding: 4px 0;">${alert.firstDetectedAt.toUTCString()} (${hoursAgo(alert.firstDetectedAt)} ago)</td></tr>
    <tr><td style="padding: 4px 12px 4px 0; color: #6b7280;">Expected</td>
        <td style="padding: 4px 0;">~${fmt(alert.expectedRate)} events/hr (7-day baseline for this hour)</td></tr>
    <tr><td style="padding: 4px 12px 4px 0; color: #6b7280;">Actual</td>
        <td style="padding: 4px 0;">${fmt(alert.actualRate)} events in the last hour</td></tr>
    <tr><td style="padding: 4px 12px 4px 0; color: #6b7280;">Drop</td>
        <td style="padding: 4px 0; color: #dc2626;"><strong>${dropPctStr}</strong></td></tr>
  </table>

  <h3 style="color: #374151; margin: 0 0 8px;">Likely Causes (in order of probability)</h3>
  <ol style="margin: 0 0 20px; padding-left: 20px; line-height: 1.8;">
    <li>Site Tag script removed from <code>${brand.domain}</code></li>
    <li>GTM container edited or tag paused</li>
    <li>Customer's site redeployed without our tag baked in</li>
    <li>CSP / security plugin started blocking <code>app.meseoapp.com</code></li>
  </ol>

  <h3 style="color: #374151; margin: 0 0 8px;">Quick Diagnostic</h3>
  <ol style="margin: 0 0 20px; padding-left: 20px; line-height: 1.8;">
    <li>Open <a href="https://${brand.domain}" style="color: #4f46e5;">https://${brand.domain}</a> in DevTools</li>
    <li>Console: type <code>window.meseo</code>
      <ul style="margin: 4px 0; list-style-type: disc; padding-left: 16px;">
        <li>Returns object → tag loaded, possible server-side issue</li>
        <li>Returns <code>undefined</code> → <strong>tag missing from site (most likely)</strong></li>
      </ul>
    </li>
    <li>Network tab: filter "meseoapp.com" — should see <code>t.js</code> loaded</li>
  </ol>

  <p style="margin: 0 0 8px;">
    <a href="${APP_URL}/site-tag-analytics?brandId=${brand.id}"
       style="background: #4f46e5; color: white; padding: 8px 16px; border-radius: 6px; text-decoration: none; display: inline-block;">
      View Dashboard →
    </a>
  </p>

  <p style="margin: 24px 0 0; color: #9ca3af; font-size: 12px;">
    This is an automated alert from the meSEO health monitor.<br>
    Alert ID: ${alert.id}
  </p>
</div>
  `.trim();

  await sendEmail([ALERT_RECIPIENT], subject, html);
}

// ─── Resolved alert ──────────────────────────────────────────────────────────

export async function sendResolvedAlert(
  brand: { id: string; name: string; domain: string },
  alert: BrandHealthAlert,
) {
  if (!ALERT_RECIPIENT) return;

  const resolvedAt = alert.resolvedAt ?? new Date();
  const downtimeMs = resolvedAt.getTime() - alert.firstDetectedAt.getTime();
  const downtimeHours = Math.round(downtimeMs / 3_600_000);
  const estimatedLoss = Math.round(alert.expectedRate * downtimeHours);

  const subject = `✅ [meSEO] ${brand.name} ingest recovered`;

  const html = `
<div style="font-family: monospace; font-size: 14px; color: #1a1a1a; max-width: 640px;">
  <h2 style="color: #16a34a; margin: 0 0 16px;">✅ Site Tag Ingest Recovered</h2>

  <table style="border-collapse: collapse; width: 100%; margin-bottom: 20px;">
    <tr><td style="padding: 4px 12px 4px 0; color: #6b7280; white-space: nowrap;">Brand</td>
        <td style="padding: 4px 0;"><strong>${brand.name}</strong></td></tr>
    <tr><td style="padding: 4px 12px 4px 0; color: #6b7280;">Recovered at</td>
        <td style="padding: 4px 0;">${resolvedAt.toUTCString()}</td></tr>
    <tr><td style="padding: 4px 12px 4px 0; color: #6b7280;">Total downtime</td>
        <td style="padding: 4px 0;">${downtimeHours} hour${downtimeHours !== 1 ? "s" : ""}</td></tr>
    <tr><td style="padding: 4px 12px 4px 0; color: #6b7280;">Est. events lost</td>
        <td style="padding: 4px 0;">~${fmt(estimatedLoss)}</td></tr>
  </table>

  <p style="margin: 0 0 8px;">
    <a href="${APP_URL}/site-tag-analytics?brandId=${brand.id}"
       style="background: #4f46e5; color: white; padding: 8px 16px; border-radius: 6px; text-decoration: none; display: inline-block;">
      View Dashboard →
    </a>
  </p>

  <p style="margin: 24px 0 0; color: #9ca3af; font-size: 12px;">
    Automated alert from the meSEO health monitor. Alert ID: ${alert.id}
  </p>
</div>
  `.trim();

  await sendEmail([ALERT_RECIPIENT], subject, html);
}
