/**
 * Auth Store
 *
 * Zustand store for authentication state management
 */

import { create } from 'zustand';
import { User, AuthState, LoginCredentials, AuthResponse } from '@/types';
import { authApi, storage } from '@/services/api';

interface AuthStore extends AuthState {
  // Actions
  login: (credentials: LoginCredentials) => Promise<void>;
  logout: () => Promise<void>;
  loadStoredAuth: () => Promise<void>;
  refreshProfile: () => Promise<void>;
  setUser: (user: User | null) => void;
  setLoading: (loading: boolean) => void;
}

export const useAuthStore = create<AuthStore>((set, get) => ({
  // Initial state
  user: null,
  token: null,
  refreshToken: null,
  isAuthenticated: false,
  isLoading: true,

  // Login action
  login: async (credentials: LoginCredentials) => {
    set({ isLoading: true });

    try {
      const response: AuthResponse = await authApi.login(
        credentials.email,
        credentials.password,
        credentials.tenantId
      );

      // Store tokens securely
      await storage.setToken(response.token);
      await storage.setRefreshToken(response.refreshToken);
      if (response.user.tenantId) {
        await storage.setTenantId(response.user.tenantId);
      }

      set({
        user: response.user,
        token: response.token,
        refreshToken: response.refreshToken,
        isAuthenticated: true,
        isLoading: false,
      });
    } catch (error) {
      set({ isLoading: false });
      throw error;
    }
  },

  // Logout action
  logout: async () => {
    set({ isLoading: true });

    try {
      await authApi.logout();
    } catch (error) {
      // Continue with local logout even if API fails
      console.warn('Logout API error:', error);
    } finally {
      await storage.clearAll();

      set({
        user: null,
        token: null,
        refreshToken: null,
        isAuthenticated: false,
        isLoading: false,
      });
    }
  },

  // Load stored auth on app startup
  loadStoredAuth: async () => {
    set({ isLoading: true });

    try {
      const token = await storage.getToken();
      const refreshToken = await storage.getRefreshToken();

      if (token) {
        // Validate token by fetching profile
        const profile = await authApi.getProfile();

        set({
          user: profile,
          token,
          refreshToken,
          isAuthenticated: true,
          isLoading: false,
        });
      } else {
        set({ isLoading: false });
      }
    } catch (error) {
      // Token invalid or expired
      await storage.clearAll();
      set({
        user: null,
        token: null,
        refreshToken: null,
        isAuthenticated: false,
        isLoading: false,
      });
    }
  },

  // Refresh user profile
  refreshProfile: async () => {
    if (!get().isAuthenticated) return;

    try {
      const profile = await authApi.getProfile();
      set({ user: profile });
    } catch (error) {
      console.warn('Failed to refresh profile:', error);
    }
  },

  // Set user directly
  setUser: (user: User | null) => {
    set({ user, isAuthenticated: !!user });
  },

  // Set loading state
  setLoading: (isLoading: boolean) => {
    set({ isLoading });
  },
}));

// Selectors
export const selectUser = (state: AuthStore) => state.user;
export const selectIsAuthenticated = (state: AuthStore) => state.isAuthenticated;
export const selectIsLoading = (state: AuthStore) => state.isLoading;
