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

export const useAuth = () => {
  const { setRefreshToken, getRefreshToken, clearRefreshToken } = useAuthStorage();

  const clearAuthData = async () => {
    userStore().resetUser();
    permissionStore().resetScopes();
    await clearRefreshToken();
  };

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

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

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

  const refresh = async () => {
    try {
      const refreshToken = await getRefreshToken();

      if (!refreshToken) {
        return Promise.reject(new Error("No refresh token available"));
      }

      const response = await api.post("/refresh-app", {
        refresh_token: refreshToken,
      });

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

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