import { NextResponse } from "next/server";
import { requireRole } from "@/lib/auth";
import {
  demoAccessEmail,
  loginCredentialEmail,
  paymentReceivedEmail,
  welcomeInstitutionEmail,
} from "@/lib/email-templates";

/** Live preview of the premium platform email templates, rendered with
    sample data (Central → Accounts → Integration & Templates). */

const TEMPLATES = ["demo", "payment", "credential", "welcome"] as const;

export async function GET(req: Request) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const type = new URL(req.url).searchParams.get("type") ?? "";
  if (!TEMPLATES.includes(type as never)) {
    return NextResponse.json({ error: "UNKNOWN_TEMPLATE" }, { status: 400 });
  }

  const base = process.env.APP_URL ?? process.env.NEXT_PUBLIC_APP_URL ?? new URL(req.url).origin;
  const loginUrl = `${base.replace(/\/+$/, "")}/login`;
  const supportEmail = "support@increlog.com";

  const tpl =
    type === "demo"
      ? demoAccessEmail({
          toName: "Md. Rahim Uddin",
          institutionName: "Sunrise Model High School",
          institutionTypeLabel: "High School",
          email: "rahim@sunrisemodel.edu.bd",
          password: "Kd7#mQx2pZ",
          code: "HS-4821",
          loginUrl,
          supportEmail,
        })
      : type === "payment"
        ? paymentReceivedEmail({
            toName: "Mrs. Sabina Akter",
            institutionName: "Sunrise Model High School",
            invoiceNo: "INV-000142",
            packageName: "Standard Package — 780 Students",
            amount: 46500,
            methodLabel: "bKash (Mobile Banking)",
            transactionRef: "TRX9X7K2LM",
            paidAt: new Date(),
            periodStart: new Date(),
            periodEnd: new Date(Date.now() + 330 * 86400000),
            totalAmount: 93000,
            paidToDate: 46500,
            dueAmount: 46500,
            billingUrl: `${base.replace(/\/+$/, "")}/portal/billing`,
            supportEmail,
          })
        : type === "credential"
          ? loginCredentialEmail({
              toName: "Abdul Karim",
              institutionName: "Sunrise Model High School — Mirpur Branch",
              parentInstitutionName: "Sunrise Model High School",
              code: "HS-5530",
              email: "karim@sunrisemodel.edu.bd",
              password: "Br9$wLn4tq",
              loginUrl,
              supportEmail,
            })
          : welcomeInstitutionEmail({
              toName: "Mrs. Sabina Akter",
              institutionName: "Sunrise Model High School",
              code: "HS-4821",
              typeLabel: "High School",
              district: "Dhaka",
              loginUrl,
              supportEmail,
            });

  return NextResponse.json({ type, subject: tpl.subject, html: tpl.html });
}
