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

interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  login: (credentials: LoginCredentials) => Promise<LoginResponse>;
  logout: () => Promise<void>;
  initialize: () => Promise<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: async () => {
          const token = authService.getToken();

          if (!token || !authService.isAuthenticated()) {
            authService.clearAuth();
            set({
              token: null,
              user: null,
              isAuthenticated: false,
              isLoading: false,
            });
            return;
          }

          try {
            const user = await authService.getCurrentUser();
            set({
              token,
              user,
              isAuthenticated: Boolean(user),
              isLoading: false,
            });
          } catch (error) {
            authService.clearAuth();
            set({
              token: null,
              user: null,
              isAuthenticated: false,
              isLoading: false,
            });
          }
        },

        login: async (credentials: LoginCredentials) => {
          try {
            set({ isLoading: true });
            const response = await authService.login(credentials);
            if (!response.mfaRequired) {
              const { user, token } = response;
              set({
                user,
                token,
                isAuthenticated: true,
                isLoading: false,
              });
            } else {
              set({ isLoading: false });
            }
            return response;
          } 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',
        storage: createJSONStorage(() => sessionStorage),
        // 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' }
  )
);
