import api from "src/api";
import { permissionStore } from "src/stores/permission";
import { userStore } from "src/stores/user";
import { useAuthStorage } from "src/composables/useAuthStorage";
import { registerPendingFcmToken } from "src/boot/push-notifications";

let refreshPromise = null;

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

  const login = async (email, password) => {
    try {
      const response = await api.post("/login-app", {
        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 doRefresh = 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);
    }
  };

  const refresh = () => {
    if (!refreshPromise) {
      refreshPromise = doRefresh().finally(() => {
        refreshPromise = null;
      });
    }
    return refreshPromise;
  };

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