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

type RequestBody = {
  displayName?: string;
  email?: string;
  avatar?: string;
};

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

  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: 409 });
  }

  const {
    displayName,
    email,
    avatar: avatarBase64
  } = (await request.json()) as RequestBody;

  let changeDisplayName = false;
  if (
    displayName !== undefined &&
    typeof displayName === "string" &&
    displayName !== userInfo.displayName
  ) {
    changeDisplayName = true;
  }

  // TODO: when we implement migadu, make sure to update the redirect
  let changeEmail = false;
  if (
    email !== undefined &&
    typeof email === "string" &&
    email !== userInfo.email
  ) {
    changeEmail = true;
  }

  let avatarBuf = undefined;
  if (
    avatarBase64 !== undefined &&
    typeof avatarBase64 === "string" &&
    avatarBase64 !== userInfo.avatar
  ) {
    avatarBuf = Buffer.from(avatarBase64, "base64");

    if (avatarBuf.length > 2_000_000) {
      return new Response(
        JSON.stringify({
          ok: false,
          error: "avatarBig"
        }),
        { status: 400 }
      );
    }
  }

  if (!changeDisplayName && !changeEmail && !avatarBuf) {
    return new Response(null, { status: 200 });
  }

  await updateUser(
    user,
    changeDisplayName ? displayName : undefined,
    changeEmail ? email : undefined,
    avatarBuf ?? undefined
  );

  logger.info(
    {
      username: user.username,
      displayName: changeDisplayName ? displayName : null,
      email: changeEmail ? email : null,
      avatar: avatarBuf ? `${avatarBuf.length} bytes` : null
    },
    "updated user"
  );

  return new Response(
    JSON.stringify({
      ok: true
    }),
    {
      status: 200
    }
  );
}
