import * as ldap from "@/ldap";
import prisma from "@/prisma";
import { getUser } from "@/auth/auth";
import { getLogger } from "@/logger";
import { registerServerSchema } from "@/schemas";

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

export async function POST(request: Request) {
  const user = await getUser();
  if (user == null) return new Response(null, { status: 401 });

  // user already has an account, don't re-register
  if (user.username != null) {
    logger.info(
      { username: user.username, id: user.id },
      `user tried to register twice`
    );
    return new Response(null, { status: 403 });
  }

  const { username, displayName, email, password, avatar } =
    await registerServerSchema.validate(await request.json());
  let avatarBuf = avatar != null ? Buffer.from(avatar, "base64") : null;

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

  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 new Response(
    JSON.stringify({
      ok: true
    }),
    { status: 201 }
  );
}
