import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { maskEmail, maskPhone } from "@/lib/notify";
import { resolveDestinations, signStepToken } from "@/lib/reset-otp";

/**
 * Step 1 of the public forgot-password flow — find the account and list the
 * channels (email / SMS) an OTP can be delivered to, WITHOUT revealing the
 * address itself. Members identify with institution code + username, admins
 * with their email. Every failure returns the same generic code so the
 * endpoint can't be used to enumerate accounts.
 */
export async function POST(req: Request) {
  const body = (await req.json().catch(() => ({}))) as {
    email?: string;
    institutionCode?: string;
    username?: string;
  };

  const userInclude = {
    studentProfile: { select: { guardianPhone: true } },
    parentOfStudent: { select: { guardianPhone: true } },
    staff: { select: { phone: true } },
    institution: { select: { phone: true } },
  } as const;

  let user = null;
  const email = (body.email ?? "").trim().toLowerCase();
  if (email) {
    user = await prisma.user.findUnique({ where: { email }, include: userInclude });
  } else {
    const code = (body.institutionCode ?? "").trim().toUpperCase();
    const username = (body.username ?? "").trim();
    if (code && username) {
      const institution = await prisma.institution.findUnique({ where: { code } });
      if (institution) {
        user = await prisma.user.findFirst({
          where: { institutionId: institution.id, username },
          include: userInclude,
        });
      }
    }
  }

  if (!user || user.status !== "ACTIVE") {
    return NextResponse.json({ error: "IDENTIFY_FAILED" }, { status: 404 });
  }

  const dest = resolveDestinations(user);
  const channels: { type: "EMAIL" | "SMS"; masked: string }[] = [];
  if (dest.email) channels.push({ type: "EMAIL", masked: maskEmail(dest.email) });
  if (dest.phone) channels.push({ type: "SMS", masked: maskPhone(dest.phone) });

  const token = await signStepToken(user.id, "identify");
  return NextResponse.json({
    token,
    name: user.name,
    channels,
    // institutions pick their theme colors; the recovery card shows a small
    // branded touch when the account belongs to one
    institution: user.institutionId
      ? await prisma.institution
          .findUnique({ where: { id: user.institutionId }, select: { name: true } })
          .then((i) => i?.name ?? null)
      : null,
  });
}
