import { create } from 'zustand';
import type { User, UserRole } from '../types/api';
import { apiClient } from './api';

interface AuthState {
  user: User | null;
  isLoading: boolean;
  isAuthenticated: boolean;
  login: (email: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  refreshAuth: () => Promise<void>;
  setUser: (user: User | null) => void;
}

export const useAuthStore = create<AuthState>((set) => ({
  user: null,
  isLoading: false,
  isAuthenticated: false,

  login: async (email: string, password: string) => {
    set({ isLoading: true });
    try {
      const response = await apiClient.login({ email, password });
      const user: User = {
        id: response.user_id,
        email: email,
        full_name: '', // Will be populated from user profile
        role: response.role as UserRole,
        auth_provider: 'local', // Local login always uses local auth
        is_active: true,
        created_at: '',
      };
      set({ user, isAuthenticated: true, isLoading: false });
    } catch (error) {
      set({ isLoading: false });
      throw error;
    }
  },

  logout: async () => {
    try {
      await apiClient.logout();
    } catch (error) {
      console.warn('Logout request failed:', error);
    } finally {
      set({ user: null, isAuthenticated: false });
    }
  },

  refreshAuth: async () => {
    set({ isLoading: true });
    try {
      const response = await apiClient.refresh();
      // Reconstruct user from refresh response
      const user: User = {
        id: response.user_id,
        email: response.email,
        full_name: response.full_name,
        role: response.role as UserRole,
        auth_provider: 'local', // Default to local, will be updated if user fetched
        is_active: true,
        created_at: '',
      };
      set({ user, isAuthenticated: true, isLoading: false });
    } catch (error) {
      set({ user: null, isAuthenticated: false, isLoading: false });
      throw error;
    }
  },

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