import { NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/prisma";
import { requireAnyRole, MEMBER_ROLES } from "@/lib/auth";

/** Member self-service password change: verifies the current password
    before accepting the new one. */
export async function PUT(req: Request) {
  const session = await requireAnyRole(MEMBER_ROLES);
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await req.json();
    const currentPassword = String(body.currentPassword ?? "");
    const newPassword = String(body.newPassword ?? "");

    if (newPassword.length < 6) {
      return NextResponse.json({ error: "PASSWORD_TOO_SHORT" }, { status: 400 });
    }

    const me = await prisma.user.findUnique({ where: { id: session.userId } });
    if (!me || !(await bcrypt.compare(currentPassword, me.passwordHash))) {
      return NextResponse.json({ error: "WRONG_PASSWORD" }, { status: 403 });
    }

    await prisma.user.update({
      where: { id: me.id },
      data: { passwordHash: await bcrypt.hash(newPassword, 10) },
      select: { id: true },
    });

    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ error: "Could not change password" }, { status: 500 });
  }
}
