import { getUser } from "@/auth/auth";
import { getUserInfo, setPassword, validateUser } from "@/ldap";
import { getLogger } from "@/logger";

type RequestBody = {
  currentPassword: string;
  newPassword: string;
};

export async function POST(request: Request) {
  const logger = getLogger("/api/changePassword");

  const user = await getUser();
  if (user == null) return new Response(null, { status: 401 });

  const userInfo = await getUserInfo(user);
  if (userInfo == null) {
    // no user info = hasn't registered yet
    return new Response(null, { status: 401 });
  }

  const { currentPassword, newPassword } =
    (await request.json()) as RequestBody;

  if (
    currentPassword == undefined ||
    typeof currentPassword !== "string" ||
    newPassword == undefined ||
    typeof newPassword !== "string"
  ) {
    return new Response(
      JSON.stringify({
        ok: false,
        error: "invalidBody"
      }),
      { status: 400 }
    );
  }

  const passwordMatches = await validateUser(user.username!, currentPassword);
  if (!passwordMatches) {
    return new Response(
      JSON.stringify({
        ok: false,
        error: "incorrectPassword"
      }),
      { status: 400 }
    );
  }

  if (newPassword.length < 12) {
    return new Response(
      JSON.stringify({
        ok: false,
        error: "passwordShort"
      }),
      { status: 400 }
    );
  }

  await setPassword(user.username!, newPassword);

  return new Response(
    JSON.stringify({
      ok: true
    }),
    {
      // I would use 204, but Next doesn't like it, so lol
      // https://github.com/vercel/next.js/pull/48354
      status: 200
    }
  );
}
