import { api } from "src/boot/axios";
import { Cookies } from "quasar";
import { permissionStore } from "src/stores/permission";
import { userStore } from "src/stores/user";

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

      if (response.status === 200) {
        const payload = response.data.payload;

        const accessTokenExpiresIn = new Date(
          new Date().getTime() + payload.expires_in * 1000,
        );

        const refreshTokenExpiresIn = new Date(
          new Date().getTime() + payload.refresh_token_expires_in * 1000,
        );

        Cookies.set("access_token", payload.access_token, {
          expires: accessTokenExpiresIn,
        });

        Cookies.set("refresh_token", payload.refresh_token, {
          expires: refreshTokenExpiresIn,
        });

        userStore().setUser(payload.user);

        await permissionStore().fetchScopes();
      }

      return response;
    } catch (error) {
      return Promise.reject(error);
    }
  };

  const logout = async () => {
    try {
      const response = await api.post("/logout");

      if (response.status === 200) {
        Cookies.remove("access_token");
        Cookies.remove("refresh_token");

        userStore().resetUser();

        permissionStore().resetScopes();
      }
    } catch (error) {
      console.error(error);
    }
  };

  const refreshToken = async () => {
    try {
      const refresh_token = Cookies.get("refresh_token");

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

      if (response.status === 200) {
        const payload = response.data.payload;

        const accessTokenExpiresIn = new Date(
          new Date().getTime() + payload.expires_in * 1000,
        );

        const refreshTokenExpiresIn = new Date(
          new Date().getTime() + payload.refresh_token_expires_in * 1000,
        );

        Cookies.set("access_token", payload.access_token, {
          expires: accessTokenExpiresIn,
        });

        Cookies.set("refresh_token", payload.refresh_token, {
          expires: refreshTokenExpiresIn,
        });

        userStore().setUser(payload.user);
      }
    } catch (error) {
      return Promise.reject(error);
    }
  };

  return {
    login,
    logout,
    refreshToken,
  };
};
