import { create } from 'zustand';

interface AuthState {
  token: string | null;
  role: string | null;
  isAuthenticated: boolean;
  setToken: (token: string) => void;
  logout: () => void;
}

// Helper para decodificar el JWT sin librerías externas
const parseJwt = (token: string) => {
  try {
    return JSON.parse(atob(token.split('.')[1]));
  } catch {
    return null;
  }
};

export const useAuthStore = create<AuthState>((set) => ({
  token: localStorage.getItem('token'),
  role: localStorage.getItem('role'),
  isAuthenticated: !!localStorage.getItem('token'),
  setToken: (token: string) => {
    const payload = parseJwt(token);
    const role = payload["http://schemas.microsoft.com/ws/2008/06/identity/claims/role"];

    localStorage.setItem('token', token);
    localStorage.setItem('role', role);
    set({ token, role, isAuthenticated: true });
  },
  logout: () => {
    localStorage.removeItem('token');
    localStorage.removeItem('role');
    set({ token: null, role: null, isAuthenticated: false });
  },
}));