import { defineStore } from 'pinia';
import { useGlobalRouter } from 'src/utils/globalRouter';
import { useGlobalQ } from 'src/utils/globalQ';

interface User {
  id: number;
  username: string;
  role: string;
}

interface UserState {
  user: User | null;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    user: null,
  }),
  getters: {
    isAuthenticated: (state): boolean => !!state.user,
  },
  actions: {
    setUser(user: User) {
      this.user = user;
    },
    getUser() {
      return this.user;
    },
    clearUser() {
      const $q = useGlobalQ();

      if (!this.user) return;
      if ($q) {
        $q?.notify({
          message: "user '" + this.user?.username + "' logged out",
          color: 'orange',
          position: 'bottom-right',
          icon: 'warning',
          timeout: 5000,
        });
      } else {
        console.error("user '" + this.user?.username + "' logged out");
      }

      this.user = null;

      const router = useGlobalRouter();

      router?.push('/').catch((err) => {
        if ($q) {
          $q?.notify({
            message: err,
            color: 'orange',
            position: 'bottom-right',
            icon: 'warning',
            timeout: 5000,
          });
        } else {
          console.error("user '" + this.user?.username + "' logged out");
        }
      });
    },

    isAuthorizedAs(roles: string[]) {
      return this.user !== null && roles.includes(this.user.role);
    },
  },
});
