// store/auth.ts
import { UserApi } from "@/api/user";
import { defineStore } from "pinia";
import router from "@/router";
export const useAuthStore = defineStore({
  id: "auth",
  state: () => ({
    /* Initialize state from local storage to enable user to stay logged in */
    user: localStorage.getItem("access_token")
      ? JSON.parse(localStorage.getItem("user"))
      : null,
    savedToken: localStorage.getItem("access_token")
      ? localStorage.getItem("access_token")
      : null,
  }),
  getters: {
    isAuthenticated: (state) => state.user && state.token,
    token: (state) => state.savedToken,
  },
  actions: {
    async login(email, password) {
      try {
        // Getting Access Token And Save It
        const responseLogin = await UserApi.login(email, password);
        const {
          result: { access_token },
        } = responseLogin;
        this.savedToken = access_token;
        localStorage.setItem("access_token", this.savedToken);

        // Getting User Data
        const responseUser = await UserApi.me();
        const user = responseUser.result;

        this.user = user;
        localStorage.setItem("user", JSON.stringify(this.user));

        router.replace("/dashboard");
      } catch (error) {
        // TODO: handle invalid credentials
        localStorage.removeItem("access_token");
        localStorage.removeItem("user");
        throw error;
      }
    },

    async fetchUserData() {
      const responseUser = await UserApi.me();
      const user = responseUser.result;
      this.user = user;
      localStorage.setItem("user", JSON.stringify(this.user));

      this.role = role;
      localStorage.setItem("role", JSON.stringify(this.role));
      return this.user;
    },

    logout() {
      this.user = null;
      this.savedToken = null;
      localStorage.removeItem("user");
      localStorage.removeItem("access_token");
      router.replace("/user/login");
    },

    removeUser() {
      this.user = null;
      localStorage.removeItem("user");
    },
  },
});
