import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import { sendMail, sendSms, sendWhatsapp } from "@/lib/notify";

/** Test the central platform credentials with a real send. */
export async function POST(req: Request) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = (await req.json().catch(() => ({}))) as { channel?: string; target?: string };
  const target = (body.target ?? "").trim();
  if (!target) return NextResponse.json({ error: "TARGET_REQUIRED" }, { status: 400 });

  try {
    if (body.channel === "EMAIL") {
      const setting = await prisma.mailSetting.findFirst({ where: { scope: "CENTRAL", active: true } });
      if (!setting) return NextResponse.json({ error: "CHANNEL_NOT_CONFIGURED" }, { status: 503 });
      await sendMail(setting, {
        to: target,
        subject: "Increlog EMS — central test email",
        text: "Test message from the central platform email settings. If you can read this, delivery works.",
      });
    } else if (body.channel === "SMS") {
      const setting = await prisma.smsSetting.findFirst({ where: { scope: "CENTRAL", active: true } });
      if (!setting) return NextResponse.json({ error: "CHANNEL_NOT_CONFIGURED" }, { status: 503 });
      await sendSms(setting, {
        phone: target,
        message: "Increlog EMS: test SMS from central platform settings. Delivery works.",
      });
    } else if (body.channel === "WHATSAPP") {
      const setting = await prisma.whatsappSetting.findFirst({ where: { scope: "CENTRAL", active: true } });
      if (!setting) return NextResponse.json({ error: "CHANNEL_NOT_CONFIGURED" }, { status: 503 });
      await sendWhatsapp(setting, {
        phone: target,
        message: "Increlog EMS: test WhatsApp message from central platform settings. Delivery works.",
      });
    } else {
      return NextResponse.json({ error: "Invalid channel" }, { status: 400 });
    }
  } catch (err) {
    console.error("central-notify-test-failed", err);
    return NextResponse.json({ error: "SEND_FAILED" }, { status: 502 });
  }

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