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;
    const store = userStore();
    store.setUser(user);
    store.accessToken = access_token;
    await permissionStore().fetchScopes();
  };

  const login = async (email, password) => {
    try {
      const response = await api.post("/login", {
        email: email,
        password: password,
        origem: 'franchisee'
      });

      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();
      }
    } catch (error) {
      console.error(error);
    }
  };

  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,
  };
};
