import { Credentials } from "@/app/api/auth/[...nextauth]/models/types";
import { ServerAction } from "@/lib/actions";
import { validate } from "@/lib/encryption";
import { DBEType } from "@/models/ErrorType";
import { postServerLog } from "@/services/logs";
import dayjs from "dayjs";
import { ResultSetHeader } from "mysql2";
import { v4 } from "uuid";

export default async function fetchUser({
  user,
  password,
  isAuth,
}: Credentials) {
  const { error, con } = await ServerAction({ isAuth });
  if (error) {
    return false;
  }

  try {
    const [rSelect] = (await con.query(
      "SELECT * FROM USERS WHERE NAME = ? OR EMAIL = ? LIMIT 1",
      Array.from({ length: 2 }).map(() => user),
    )) as any[];

    if (!rSelect.length) {
      return false;
    }

    const first = rSelect[0];

    const isValid = await validate(password, first.PASSWORD);

    if (!isValid) {
      return false;
    }

    const expire_date = dayjs().add(30, "day").toDate();

    const tId = v4();

    const [rInsert] = await con.query<ResultSetHeader>(
      "INSERT INTO SESSIONS (ID, USER, TOKEN_EXPIRE_DATE) VALUES (?, ?, ?)",
      [tId, first.ID, expire_date],
    );

    const formattedUser = {
      id: first.ID,
      tId,
      name: first.NAME,
      email: first.EMAIL,
      permissions: first.PERMISSIONS,
    };

    return formattedUser;
  } catch (error) {
    await postServerLog({ type: DBEType.ERROR, log: error });
  } finally {
    con.release();
  }
}
