"use server";

import { AuthOption } from "@/app/api/auth/[...nextauth]/models/AuthOption";
import { getConnection } from "@/database/configuration/connection";
import { getDictionary } from "@/dictionaries";
import { DBEType } from "@/models/ErrorType";
import { postServerLog } from "@/services/logs";
import { ResultSetHeader, RowDataPacket } from "mysql2";
import { getServerSession } from "next-auth";
import { getLocale } from "../locales";

export default async function ServerAction({
  isAuth = true,
}: ServerAction = {}) {
  const dict = await getDictionary(getLocale());
  const con = await getConnection();

  let callback: string | undefined;

  if ("error" in con) {
    return { error: { callback, message: dict.alerts.general.connection_fail } };
  }

  try {
    if (!isAuth) {
      return { con, dict };
    }

    const session: any = await getServerSession(AuthOption);

    const { user } = session

    const [result] = await con.query<RowDataPacket[]>(
      "SELECT * FROM SESSIONS WHERE USER = ? AND EXPIRED = 0 AND TOKEN_EXPIRE_DATE > NOW()",
      [user?.id],
    );

    if (result.length === 0) {
      callback = `${process.env.NEXT_PUBLIC_URL}/error?callbackUrl=/auth/login&status=419&action=SIGN_OUT`;

      const [result] = await con.query<ResultSetHeader>(
        "UPDATE SESSIONS SET EXPIRED = ? WHERE USER = ?",
        [1, user?.id],
      );

      con.release();

      if (result.affectedRows === 0) {
        throw new Error(
          "Session expired but can't update in database, please remove manually",
        );
      }

      throw new Error("Session expired");
    }

    return { con, dict };
  } catch (error) {
    await postServerLog({
      type: DBEType.ERROR,
      log: error,
    });

    return {
      dict,
      con,
      error: { callback, message: dict.alerts.general.unexpected_error },
    };
  }
}
