/* global defineEventHandler, getCookie, setCookie, readBody, createError */
import crypto from "crypto";

import { database, data } from "../utils/database";
import { isString } from "../utils/isString";
import { cookieSettings } from "../utils/rootUtils";
import Snowflake from "~/utils/snowflake";

export function getPasswordHash(password: string) {
  return crypto.createHmac("sha512", "42")
    .update(password)
    .digest();
}

export default defineEventHandler(async (e) => {
  if (getCookie(e, "token"))
    throw createError({ statusCode: 501, message: "Case not implemented: logging in while cookie is set" });
  await new Promise(resolve => setTimeout(resolve, 420));
  const data = await readBody(e);

  const login = data.login;
  const password = data.password;

  if (!isString(login)) throw createError({ statusCode: 400, message: "Login is not string." });
  if (!isString(password)) throw createError({ statusCode: 400, message: "Password is not string." });

  const hashedPassword = getPasswordHash(password);

  const [account] = await database.query(
    "SELECT CONVERT(`id`, CHAR(32)) AS `id` from `users` WHERE `username` = ? AND `password` = ? LIMIT 1",
    [login, hashedPassword],
  )as unknown as data<{id: string}>;

  if (account.length === 0) throw createError({ statusCode: 400, message: "Invalid username or password." });

  const sessionId = new Snowflake().toString();

  await database.query(
    "INSERT INTO `sessions` (`id`, `user`) VALUES ( ? , ? )",
    [sessionId, account[0].id],
  );
  setCookie(e, "token", sessionId, cookieSettings);
  return { message: "Login successful", token: sessionId };
});