"use server";

import * as ldap from "@/ldap";
import prisma from "@/prisma";
import { getUser } from "@/auth/auth";
import { getLogger } from "@/logger";
import { RegisterSchema, registerSchema } from "@/schemas";
import { ActionResponse } from ".";

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

export default async function register(
  data: RegisterSchema
): Promise<ActionResponse> {
  const user = await getUser();

  if (user == null) {
    return { ok: false, error: "invalidAuth" };
  }

  if (user.username != null) {
    logger.info(
      { username: user.username, id: user.id },
      `user tried to register twice`
    );
    return { ok: false, error: "invalidAuth" };
  }

  const { username, displayName, email, password, avatar } =
    await registerSchema.parse(data);
  let avatarBuf = null;
  if (avatar != null) {
    const parts = avatar.split(",");
    const data = parts.length === 2 ? parts[1] : parts[0];
    avatarBuf = Buffer.from(data, "base64");
  }

  const users = await ldap.getUsers();
  for (const user of users) {
    if (user.id.toLowerCase() === username.toLowerCase()) {
      return {
        ok: false,
        error: "usernameTaken"
      };
    }
  }

  await ldap.createUser(username, displayName, email, avatarBuf ?? undefined);
  await ldap.setPassword(username, password);

  const outputUser = await prisma.user.update({
    where: {
      id: user.id
    },
    data: {
      username
    }
  });

  logger.info(outputUser, "registered user");
  return { ok: true };
}
