import { IGetProfileResponse_DTO, ILogin_DTO, ILogin_Response_DTO } from "@shared/contexts";
import secureLocalStorage from "react-secure-storage";
import { IAuthActions } from "../hooks";
import { createAxiosInstance } from "./axiosInstance";

export const createAxiosAuthActions = (
  apiUrl: string,
  httpClient = createAxiosInstance()
): IAuthActions => ({
  login: async ({ email, password }: ILogin_DTO) => {
    secureLocalStorage.clear();

    try {
      const result = await httpClient.request<ILogin_Response_DTO>({
        url: `${apiUrl}/auth/login`,
        method: "POST",
        data: {
          email,
          password,
        },
      });

      const { data } = result;
      secureLocalStorage.setItem("uecko.auth", data);

      return {
        success: true,
        data,
      };
    } catch (error) {
      return {
        success: false,
        error: {
          message: "Login failed",
          name: "Invalid email or password",
        },
      };
    }
  },

  logout: () => {
    secureLocalStorage.clear();

    return Promise.resolve({
      success: true,
      redirectTo: "/login",
    });
  },

  check: () => {
    const authUser = secureLocalStorage.getItem("uecko.auth") as ILogin_Response_DTO;
    const isAuthenticated = !!authUser?.token;

    if (!isAuthenticated) secureLocalStorage.clear();

    return Promise.resolve(
      isAuthenticated
        ? {
            authenticated: true,
          }
        : {
            authenticated: false,
            redirectTo: "/login",
          }
    );
  },

  getProfile: async () => {
    /**
     *  id: string;
     *  name: string;
     *  email: string;
     *  lang_code: string;
     *  roles: string[];
     */

    try {
      const result = await httpClient.request<IGetProfileResponse_DTO>({
        url: `${apiUrl}/profile`,
        method: "GET",
      });

      const { data: profile } = result;
      const authUser = secureLocalStorage.getItem("uecko.auth") as ILogin_Response_DTO;

      if (authUser?.id === profile?.id) {
        secureLocalStorage.setItem("uecko.profile", profile);
        return Promise.resolve(profile);
      }
      return Promise.resolve(null);
    } catch (error) {
      return Promise.resolve(null);
    }
  },

  onError: (error: any) => {
    secureLocalStorage.clear();
    return Promise.resolve({
      error,
      logout: true,
    });
  },
});
