import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { apiService } from '@/services/api';
import { tokenManager } from '@/utils/token-manager';
import type { User, LoginRequest, RegisterRequest, ApiError } from '@/types';

interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: ApiError | null;
}

interface AuthActions {
  login: (credentials: LoginRequest) => Promise<void>;
  register: (userData: RegisterRequest) => Promise<void>;
  logout: () => Promise<void>;
  refreshUser: () => Promise<void>;
  clearError: () => void;
  setLoading: (loading: boolean) => void;
  checkAuthStatus: () => Promise<void>;
}

export const useAuthStore = create<AuthState & AuthActions>()(
  persist(
    set => ({
    // État initial
    user: null,
    isAuthenticated: false,
    isLoading: false,
    error: null,

    // Actions
    login: async (credentials: LoginRequest) => {
      set({ isLoading: true, error: null });
      try {
        const response = await apiService.login(credentials);
        
        // Stocker les tokens de manière sécurisée
        // CORRECTION DURABLE: Passer le flag remember_me pour la persistance
        tokenManager.setTokens(
          response.tokens.access_token,
          response.tokens.refresh_token,
          credentials.remember_me || false
        );
        
        set({
          user: response.user,
          isAuthenticated: true,
          isLoading: false,
          error: null,
        });
      } catch (error: any) {
        set({
          error: error as ApiError,
          isLoading: false,
          isAuthenticated: false,
          user: null,
        });
        throw error;
      }
    },

    register: async (userData: RegisterRequest) => {
      set({ isLoading: true, error: null });
      try {
        const response = await apiService.register(userData);
        
        // Stocker les tokens de manière sécurisée
        tokenManager.setTokens(
          response.tokens.access_token,
          response.tokens.refresh_token,
          false
        );
        
        set({
          user: response.user,
          isAuthenticated: true,
          isLoading: false,
          error: null,
        });
      } catch (error: any) {
        set({
          error: error as ApiError,
          isLoading: false,
          isAuthenticated: false,
          user: null,
        });
        throw error;
      }
    },

    logout: async () => {
      set({ isLoading: true });
      try {
        // T0179: Utiliser la fonction logout du service API auth
        const { logout } = await import('@/services/api/auth');
        await logout();
      } catch (error) {
        console.error('Logout error:', error);
      } finally {
        // T0179: Nettoyer les tokens de manière sécurisée
        // La fonction logout du service API nettoie déjà les tokens,
        // mais on nettoie aussi via tokenManager pour compatibilité
        tokenManager.clearTokens();
        
        set({
          user: null,
          isAuthenticated: false,
          isLoading: false,
          error: null,
        });
      }
    },

    refreshUser: async () => {
      if (!tokenManager.isAuthenticated()) {
        set({ user: null, isAuthenticated: false });
        return;
      }

      set({ isLoading: true });
      try {
        const user = await apiService.getCurrentUser();
        set({
          user,
          isAuthenticated: true,
          isLoading: false,
          error: null,
        });
      } catch (error: any) {
        // Si l'erreur est 401, l'API service gère déjà le refresh automatiquement
        // On nettoie simplement l'état si le refresh échoue
        if (error.status === 401) {
          tokenManager.clearTokens();
        }
        
        set({
          error: error as ApiError,
          isLoading: false,
          isAuthenticated: false,
          user: null,
        });
      }
    },

    checkAuthStatus: async () => {
      if (!tokenManager.isAuthenticated()) {
        set({ user: null, isAuthenticated: false });
        return;
      }

      set({ isLoading: true });
      try {
        const user = await apiService.getCurrentUser();
        set({
          user,
          isAuthenticated: true,
          isLoading: false,
          error: null,
        });
      } catch (error: any) {
        // Si l'erreur est 401, nettoyer l'état d'authentification
        if (error.status === 401) {
          tokenManager.clearTokens();
          set({
            user: null,
            isAuthenticated: false,
            isLoading: false,
            error: null,
          });
        } else {
          set({
            error: error as ApiError,
            isLoading: false,
            isAuthenticated: false,
            user: null,
          });
        }
      }
    },

    clearError: () => set({ error: null }),
    setLoading: (loading: boolean) => set({ isLoading: loading }),
  }),
    {
      name: 'auth-storage',
      partialize: state => ({
        user: state.user,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
);
