import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { UserInfo } from '@horux/shared';

interface AuthState {
  user: UserInfo | null;
  isAuthenticated: boolean;
  _hasHydrated: boolean;
  setUser: (user: UserInfo | null) => void;
  setTokens: (accessToken: string, refreshToken: string) => void;
  logout: () => void;
  setHasHydrated: (state: boolean) => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      user: null,
      isAuthenticated: false,
      _hasHydrated: false,
      setUser: (user) => set({ user, isAuthenticated: !!user }),
      setTokens: (accessToken, refreshToken) => {
        localStorage.setItem('accessToken', accessToken);
        localStorage.setItem('refreshToken', refreshToken);
      },
      logout: () => {
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        // Limpia impersonación de admin global — sin esto, si un admin
        // global usa el TenantSelector y luego logout, el siguiente user
        // que entre en este browser hereda el X-View-Tenant y el tenant
        // middleware le rechaza con 403.
        localStorage.removeItem('horux-tenant-view');
        set({ user: null, isAuthenticated: false });
      },
      setHasHydrated: (state) => set({ _hasHydrated: state }),
    }),
    {
      name: 'horux-auth',
      partialize: (state) => ({ user: state.user, isAuthenticated: state.isAuthenticated }),
      onRehydrateStorage: () => (state) => {
        state?.setHasHydrated(true);
      },
    }
  )
);
