import { execSync } from "node:child_process";
import { defineEventHandler, setResponseStatus, readBody } from "h3";

import { database } from "../utils/database";
import { isFirstRun } from "./firstRun.get";
import { getPasswordHash } from "./login.post";
import Snowflake from "~/utils/snowflake";

import { createError } from "#imports";

export default defineEventHandler(async (e) => {
  if (!isFirstRun()) {
    setResponseStatus(e, 404);
    return null;
  }

  const body = await readBody(e);
  if (typeof body !== "object") throw createError({ message: "Invalid body", statusCode: 400 });
  const username = body.username;
  if (typeof username !== "string") throw createError({ message: "username is not string", statusCode: 400 });
  const password = body.password;
  if (typeof password !== "string") throw createError({ message: "password is not string", statusCode: 400 });
  const email = body.email;
  if (typeof email !== "string") throw createError({ message: "email is not string", statusCode: 400 });

  execSync("npx prisma db push --force-reset");
  database.user.create({
    data: {
      id: new Snowflake().state,
      username,
      email,
      password: getPasswordHash(password),
    },
  });
  return null;
});