import { defineStore } from "pinia";
import type { AuthSessionResponse } from "../../contractsAuth";
import { clearAuthSession, getAuthSession, setAuthSession, subscribeToAuthSession } from "../../authSession";

export const useAuthStore = defineStore("auth", {
  state: () => ({
    session: getAuthSession() as AuthSessionResponse | null,
    busy: false,
    initialized: false,
  }),
  getters: {
    isAuthenticated: (state) => state.session != null,
    email: (state) => state.session?.email ?? null,
    roles: (state) => state.session?.roles ?? [],
    canAccessGm: (state) => (state.session?.roles ?? []).some((role) => role === "gm" || role === "admin"),
    accessToken: (state) => state.session?.accessToken ?? null,
  },
  actions: {
    setSession(session: AuthSessionResponse | null) {
      this.session = session;
      setAuthSession(session);
    },
    clearSession() {
      this.session = null;
      clearAuthSession();
    },
    setBusy(busy: boolean) {
      this.busy = busy;
    },
    initialize() {
      if (this.initialized) {
        return;
      }

      this.initialized = true;
      subscribeToAuthSession((session) => {
        this.session = session as AuthSessionResponse | null;
      });
    },
  },
});
