// Auth Store (Zustand)
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { authService } from '@/services/auth/authService';
import type { User, LoginCredentials } from '@/types';

interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  login: (credentials: LoginCredentials) => Promise<void>;
  logout: () => Promise<void>;
  initialize: () => void;
  checkPermission: (permission: string) => boolean;
  isDBISLevel: () => boolean;
}

export const useAuthStore = create<AuthState>()(
  devtools(
    persist(
      (set, get) => ({
        user: null,
        token: null,
        isAuthenticated: false,
        isLoading: true,

        initialize: () => {
          const token = authService.getToken();
          const user = authService.getUser();

          if (token && user && authService.isAuthenticated()) {
            set({
              token,
              user,
              isAuthenticated: true,
              isLoading: false,
            });
          } else {
            authService.clearAuth();
            set({
              token: null,
              user: null,
              isAuthenticated: false,
              isLoading: false,
            });
          }
        },

        login: async (credentials: LoginCredentials) => {
          try {
            set({ isLoading: true });
            const { user, token } = await authService.login(credentials);
            set({
              user,
              token,
              isAuthenticated: true,
              isLoading: false,
            });
          } catch (error) {
            set({ isLoading: false });
            throw error;
          }
        },

        logout: async () => {
          await authService.logout();
          set({
            user: null,
            token: null,
            isAuthenticated: false,
          });
        },

        checkPermission: (permission: string): boolean => {
          const { user } = get();
          if (!user) return false;
          if (user.permissions.includes('all')) return true;
          return user.permissions.includes(permission);
        },

        isDBISLevel: (): boolean => {
          const { user } = get();
          if (!user) return false;
          return ['DBIS_Super_Admin', 'DBIS_Ops', 'DBIS_Risk'].includes(user.role);
        },
      }),
      {
        name: 'auth-storage',
        // Only persist user data, not token (token is in sessionStorage for security)
        partialize: (state) => ({
          user: state.user,
          // Don't persist token or isAuthenticated for security
        }),
      }
    ),
    { name: 'AuthStore' }
  )
);

