import { browser } from "$app/environment"; import { goto } from "$app/navigation"; interface Usuario { _id: string; matricula: string; nome: string; email: string; funcionarioId?: string; role: { _id: string; nome: string; nivel: number; setor?: string; }; primeiroAcesso: boolean; } interface AuthState { usuario: Usuario | null; token: string | null; carregando: boolean; } class AuthStore { private state = $state({ usuario: null, token: null, carregando: true, }); constructor() { if (browser) { this.carregarDoLocalStorage(); } } get usuario() { return this.state.usuario; } get token() { return this.state.token; } get carregando() { return this.state.carregando; } get autenticado() { return !!this.state.usuario && !!this.state.token; } get isAdmin() { return this.state.usuario?.role.nivel === 0; } get isTI() { return this.state.usuario?.role.nome === "ti" || this.isAdmin; } get isRH() { return this.state.usuario?.role.nome === "rh" || this.isAdmin; } login(usuario: Usuario, token: string) { this.state.usuario = usuario; this.state.token = token; this.state.carregando = false; if (browser) { localStorage.setItem("auth_token", token); localStorage.setItem("auth_usuario", JSON.stringify(usuario)); } } logout() { this.state.usuario = null; this.state.token = null; this.state.carregando = false; if (browser) { localStorage.removeItem("auth_token"); localStorage.removeItem("auth_usuario"); goto("/"); } } setCarregando(carregando: boolean) { this.state.carregando = carregando; } private carregarDoLocalStorage() { const token = localStorage.getItem("auth_token"); const usuarioStr = localStorage.getItem("auth_usuario"); if (token && usuarioStr) { try { const usuario = JSON.parse(usuarioStr); this.state.usuario = usuario; this.state.token = token; } catch (error) { console.error("Erro ao carregar usuário do localStorage:", error); this.logout(); } } this.state.carregando = false; } } export const authStore = new AuthStore();