/* global defineEventHandler, createError, getCookie */

import { database, data } from "~/server/utils/database";

const endpointsWithoutAuth: string[] = [
  "/dbtest",
  "/echo",
  "/hi",
  "/login",
  "/logout",
];

export default defineEventHandler(async (e) => {
  const endpoint = e.path?.match(/^\/api(\/.*)/)?.[1];

  // if client does not access api
  if (!endpoint) return;

  for (const i of endpointsWithoutAuth)
    // if accessed endpoint doesn't require auth
    if (endpoint.startsWith(i)) return;

  const token = getCookie(e, "token");
  if (!await isAuthorised(token))
    throw createError({ statusCode: 401, message: "Unauthorized" });
});

/**
 * Checks if the token is authorised
 * @param token the token to ckeck
 */
export async function isAuthorised(token: string | undefined): Promise<boolean> {
  if (!token) return false;
  const [[session]] = await database.query(
    "SELECT EXISTS(SELECT `id` FROM `sessions` WHERE `id` = ? AND `expiry_date` >= NOW()) as `logged_in`",
    [token],
  ) as unknown as data<{logged_in: number}>;

  return session.logged_in === 1;
}