/**
 * POST /api/admin/brand-health/test-email
 *
 * Sends both the degraded and resolved email templates to
 * ALERT_EMAIL_RECIPIENT using synthetic data, so you can verify
 * delivery without waiting for a real alert.
 *
 * Usage from DevTools:
 *   fetch("/api/admin/brand-health/test-email", { method: "POST" })
 *     .then(r => r.json()).then(console.log)
 */

import { NextResponse } from "next/server";
import { requireSuperadmin } from "@/lib/admin-auth";
import { sendDegradedAlert, sendResolvedAlert } from "@/lib/services/brand-health-email";
import type { BrandHealthAlert } from "@prisma/client";

export const dynamic = "force-dynamic";

export async function POST() {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const fakeBrand = { id: "test-brand-id", name: "Fairway Lawns (TEST)", domain: "fairwaylawns.com" };

  const now = new Date();
  const twoHoursAgo = new Date(now.getTime() - 2 * 3_600_000);

  const fakeAlert = {
    id: "test-alert-id",
    brandId: fakeBrand.id,
    status: "down",
    firstDetectedAt: twoHoursAgo,
    alertSentAt: now,
    resolvedAt: now,
    expectedRate: 520,
    actualRate: 12,
    dropPct: 0.977,
    consecutiveHoursDegraded: 2,
    lastCheckedAt: now,
    createdAt: twoHoursAgo,
    updatedAt: now,
  } satisfies BrandHealthAlert;

  const results: Record<string, { success: boolean; error?: string }> = {};

  try {
    await sendDegradedAlert(fakeBrand, fakeAlert);
    results.degraded = { success: true };
  } catch (err) {
    results.degraded = { success: false, error: err instanceof Error ? err.message : String(err) };
  }

  try {
    await sendResolvedAlert(fakeBrand, fakeAlert);
    results.resolved = { success: true };
  } catch (err) {
    results.resolved = { success: false, error: err instanceof Error ? err.message : String(err) };
  }

  return NextResponse.json({ recipient: process.env.ALERT_EMAIL_RECIPIENT ?? "(not set)", results });
}
