import { ConfigType } from "../types/type";

// get the current url pathname
const currentUrl = new URL(window.location.href).pathname;

/**
 * Checks if the user is authenticated by verifying the token stored in the local storage.
 * If the user is not authenticated, it redirects them to the login page.
 *
 * @param {ConfigType} config - An object containing the necessary configurations for authentication.
 * @param {string} config.base_api_route_url - The base URL of the API.
 * @param {string} config.ping_route_url - The route to ping to check authentication.
 * @param {string[]} config.allowed_path - An array of allowed routes.
 * @param {string} config.desallowed_redirect_path - The path to redirect if the user is not allowed.
 * @param {string} config.disallowed_path - The route to redirect if the user is not allowed.
 * @param {string} config.login_path - The path to the login page.
 * @param {string} config.signup_path - The path to the signup page.
 * @param {string} [config.session_storage_name="token"] - The name of the session storage.
 * @param {string | undefined} config.csrf_cookies_route_url - The url of the csrf cookies.
 * @return {Promise<boolean | void | undefined>} A promise that resolves to true if the user is authenticated,
 *                                               or undefined if an error occurs.
 */
const isAuth = (config: ConfigType): Promise<boolean | void | undefined> => {

   // get the local storage using the session storage name provided by the user in config. default is 3kjos_fortress_user_credentials
   const storage = JSON.parse(localStorage.getItem(config.session_storage_name!)!);
   if (!storage ) {
      // redirect user to login page only if the route user want to access is not allowed
      if(!config.allowed_path!.includes(currentUrl!)) window.location.href = config.login_path;
   }
   if (storage && !('token' in storage)){
      // redirect user to login page only if the route user want to access is not allowed
      if(!config.allowed_path!.includes(currentUrl!)) window.location.href = config.login_path;
   }

   // if user is authenticated, return true
   const token = storage?.token
   const requestConfig: RequestInit = { headers: { Accept: "application/json", Authorization: `Bearer ${token}` } };

   const response: Promise<boolean | void | undefined> = fetch(config.base_api_route_url + config.ping_route_url, requestConfig).then((response) => {
      if (response.status === 200) {
         return true
      }
   }).catch((error) => {
      // redirect user to login page only if the route user want to access is not allowed
      if (!config.allowed_path!.includes(currentUrl!)) window.location.href = config.login_path;
   })

   return response
}

export default isAuth