"use server";

import { AboutMeSchema, aboutMeSchema } from "@/schemas";
import { ActionResponse } from ".";
import { getLogger } from "@/logger";
import { getUser } from "@/auth/auth";
import { getUserInfo, updateUser } from "@/ldap";

const logger = getLogger("/actions/update");

export default async function update(
  data: AboutMeSchema
): Promise<ActionResponse> {
  const user = await getUser();
  if (user == null) {
    return { ok: false, error: "invalidAuth" };
  }

  const userInfo = await getUserInfo(user);
  if (userInfo == null) {
    // no user info = hasn't registered yet
    return { ok: false, error: "invalidAuth" };
  }

  const { displayName, email, avatar } = await aboutMeSchema.parse(data);

  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 (
    avatar !== undefined &&
    typeof avatar === "string" &&
    avatar !== userInfo.avatar
  ) {
    const parts = avatar.split(",");
    const data = parts.length === 2 ? parts[1] : parts[0];
    avatarBuf = Buffer.from(data, "base64");

    if (avatarBuf.length > 2_000_000) {
      return {
        ok: false,
        error: "avatarBig"
      };
    }
  }

  if (!changeDisplayName && !changeEmail && !avatarBuf) {
    return { ok: true };
  }

  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 { ok: true };
}
