import api from "src/api";
import { permissionStore } from "src/stores/permission";
import { userStore } from "src/stores/user";

export const useAuth = () => {
  const setAuthDataFromPayload = async (tokens) => {
    const { access_token, user } = tokens;
    userStore().user = user;
    userStore().accessToken = access_token;
    await permissionStore().fetchScopes();
  };

  const login = async (identifier, password, options = {}) => {
    try {
      const response = await api.post(
        "/login",
        {
          identifier,
          password,
          tipo: "associado",
        },
        options,
      );

      if (response.status === 200) {
        await setAuthDataFromPayload(response.data.payload);
      }
      return response;
    } catch (error) {
      return Promise.reject(error);
    }
  };

  const logout = async () => {
    try {
      const response = await api.post("/logout");
      if (response.status === 200) {
        userStore().resetUser();
        permissionStore().resetScopes();
      }
    } catch {
      userStore().resetUser();
      permissionStore().resetScopes();
    }
  };

  const refresh = async () => {
    try {
      const response = await api.post("/refresh");
      if (response.status === 200) {
        await setAuthDataFromPayload(response.data.payload);
      }
      return response;
    } catch (error) {
      return Promise.reject(error);
    }
  };

  return {
    login,
    logout,
    refresh,
    setAuthDataFromPayload,
  };
};
