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

/** Send a test message through the credentials the flow would really use
    (institution row first, central fallback) — validates config from the
    Control Panel before users depend on it. */
export async function POST(req: Request) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session?.institutionId) {
    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 resolved = await resolveMailSetting(session.institutionId);
      if (!resolved) return NextResponse.json({ error: "CHANNEL_NOT_CONFIGURED" }, { status: 503 });
      await sendMail(resolved.setting, {
        to: target,
        subject: "Increlog EMS — test email",
        text: "This is a test message from your institution's OTP email settings. If you can read this, delivery works.",
      });
    } else if (body.channel === "SMS") {
      const resolved = await resolveSmsSetting(session.institutionId);
      if (!resolved) return NextResponse.json({ error: "CHANNEL_NOT_CONFIGURED" }, { status: 503 });
      await sendSms(resolved.setting, {
        phone: target,
        message: "Increlog EMS: test SMS from your OTP settings. Delivery works.",
      });
    } else if (body.channel === "WHATSAPP") {
      const resolved = await resolveWhatsappSetting(session.institutionId);
      if (!resolved) return NextResponse.json({ error: "CHANNEL_NOT_CONFIGURED" }, { status: 503 });
      await sendWhatsapp(resolved.setting, {
        phone: target,
        message: "Increlog EMS: test WhatsApp message from your settings. Delivery works.",
      });
    } else {
      return NextResponse.json({ error: "Invalid channel" }, { status: 400 });
    }
  } catch (err) {
    console.error("notify-test-failed", err);
    return NextResponse.json({ error: "SEND_FAILED" }, { status: 502 });
  }

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