import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import { sendCentralMail } from "@/lib/central-mail";
import { appBaseUrl, loginCredentialEmail } from "@/lib/email-templates";

type Params = { params: Promise<{ id: string }> };

/** Reset an account's password (central controller action). */
export async function PATCH(req: Request, { params }: Params) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  const body = await req.json().catch(() => ({}));
  const password = String(body.password ?? "");

  if (password.length < 6) {
    return NextResponse.json({ error: "Password must be at least 6 characters" }, { status: 400 });
  }

  const existing = await prisma.user.findUnique({
    where: { id: Number(id) },
    select: {
      id: true,
      role: true,
      institutionId: true,
      institution: { select: { name: true, code: true, parent: { select: { name: true } } } },
    },
  });
  if (!existing) return NextResponse.json({ error: "Account not found" }, { status: 404 });

  try {
    const bcrypt = (await import("bcryptjs")).default;
    const account = await prisma.user.update({
      where: { id: Number(id) },
      data: { passwordHash: await bcrypt.hash(password, 10) },
      select: { id: true, name: true, email: true, role: true },
    });

    // Institution admins get the new credential by email — never blocks the reset
    if (account.role === "INSTITUTION_ADMIN" && account.email && existing.institution) {
      try {
        const tpl = loginCredentialEmail({
          toName: account.name,
          institutionName: existing.institution.name,
          parentInstitutionName: existing.institution.parent?.name ?? null,
          code: existing.institution.code,
          email: account.email,
          password,
          loginUrl: `${appBaseUrl()}/login`,
          reset: true,
        });
        await sendCentralMail({
          to: account.email,
          subject: tpl.subject,
          html: tpl.html,
          text: tpl.text,
          institutionId: existing.institutionId,
        });
      } catch (err) {
        console.error("reset-credential-mail-failed", err);
      }
    }

    return NextResponse.json({ account });
  } catch {
    return NextResponse.json({ error: "Could not reset password" }, { status: 500 });
  }
}
