import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import { toMailView, toSmsView, toWhatsappView } from "@/lib/notify";

/** Central panel → platform-wide Email/SMS/WhatsApp credentials (scope CENTRAL)
    and the document-verification fallback toggles. They serve central
    accounts, act as the fallback for institutions without their own setup,
    and (verification) decide which prints carry QR codes by default. */

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

  const [mail, sms, whatsapp, verification, stats] = await Promise.all([
    prisma.mailSetting.findFirst({ where: { scope: "CENTRAL" }, orderBy: { id: "asc" } }),
    prisma.smsSetting.findFirst({ where: { scope: "CENTRAL" }, orderBy: { id: "asc" } }),
    prisma.whatsappSetting.findFirst({ where: { scope: "CENTRAL" }, orderBy: { id: "asc" } }),
    prisma.verificationSetting.findFirst({ where: { scope: "CENTRAL" }, orderBy: { id: "asc" } }),
    prisma.verificationCode.aggregate({ _count: { id: true }, _sum: { scans: true } }),
  ]);
  return NextResponse.json({
    mail: toMailView(mail),
    sms: toSmsView(sms),
    whatsapp: toWhatsappView(whatsapp),
    verification: {
      result: verification?.result ?? true,
      examSchedule: verification?.examSchedule ?? true,
      inventory: verification?.inventory ?? true,
      configured: !!verification,
      stats: { codes: stats._count.id, scans: stats._sum.scans ?? 0 },
    },
  });
}

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

  const body = (await req.json().catch(() => ({}))) as {
    mail?: Record<string, unknown>;
    sms?: Record<string, unknown>;
    whatsapp?: Record<string, unknown>;
    verification?: { result?: boolean; examSchedule?: boolean; inventory?: boolean };
  };
  const str = (v: unknown, fallback = "") => (typeof v === "string" ? v.trim() : fallback);
  const num = (v: unknown, fallback: number) => {
    const n = Number(v);
    return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback;
  };

  if (body.verification) {
    const v = body.verification;
    const data = {
      result: v.result !== false,
      examSchedule: v.examSchedule !== false,
      inventory: v.inventory !== false,
      active: true,
    };
    const existing = await prisma.verificationSetting.findFirst({ where: { scope: "CENTRAL" } });
    if (existing) await prisma.verificationSetting.update({ where: { id: existing.id }, data });
    else await prisma.verificationSetting.create({ data: { ...data, scope: "CENTRAL", institutionId: null } });
  }

  if (body.mail) {
    const m = body.mail;
    const host = str(m.host);
    const fromEmail = str(m.fromEmail);
    const existing = await prisma.mailSetting.findFirst({ where: { scope: "CENTRAL" } });
    const password = str(m.password) || existing?.password || "";
    if (!host || !fromEmail || !password) {
      return NextResponse.json({ error: "MAIL_FIELDS_REQUIRED" }, { status: 400 });
    }
    const data = {
      host,
      port: num(m.port, 587),
      secure: m.secure !== false,
      username: str(m.username),
      password,
      fromEmail,
      fromName: str(m.fromName, "Increlog EMS"),
      active: m.active !== false,
    };
    if (existing) await prisma.mailSetting.update({ where: { id: existing.id }, data });
    else await prisma.mailSetting.create({ data: { ...data, scope: "CENTRAL", institutionId: null } });
  }

  if (body.sms) {
    const s = body.sms;
    const apiUrl = str(s.apiUrl);
    if (!apiUrl) return NextResponse.json({ error: "SMS_FIELDS_REQUIRED" }, { status: 400 });
    const existing = await prisma.smsSetting.findFirst({ where: { scope: "CENTRAL" } });
    const data = {
      apiUrl,
      method: str(s.method, "POST") === "GET" ? "GET" : "POST",
      senderId: str(s.senderId) || null,
      authUsername: str(s.authUsername) || null,
      authPassword: str(s.authPassword) || existing?.authPassword || null,
      bodyTemplate: str(s.bodyTemplate) || null,
      headersRaw: str(s.headersRaw) || null,
      active: s.active !== false,
    };
    if (existing) await prisma.smsSetting.update({ where: { id: existing.id }, data });
    else await prisma.smsSetting.create({ data: { ...data, scope: "CENTRAL", institutionId: null } });
  }

  if (body.whatsapp) {
    const w = body.whatsapp;
    const apiUrl = str(w.apiUrl);
    if (!apiUrl) return NextResponse.json({ error: "WHATSAPP_FIELDS_REQUIRED" }, { status: 400 });
    const existing = await prisma.whatsappSetting.findFirst({ where: { scope: "CENTRAL" } });
    const data = {
      apiUrl,
      method: str(w.method, "POST") === "GET" ? "GET" : "POST",
      senderId: str(w.senderId) || null,
      authToken: str(w.authToken) || existing?.authToken || null,
      bodyTemplate: str(w.bodyTemplate) || null,
      headersRaw: str(w.headersRaw) || null,
      active: w.active !== false,
    };
    if (existing) await prisma.whatsappSetting.update({ where: { id: existing.id }, data });
    else await prisma.whatsappSetting.create({ data: { ...data, scope: "CENTRAL", institutionId: null } });
  }

  return NextResponse.json({ ok: true });
}
