import { create } from 'zustand';
import api from '../utils/api';

const useAuthStore = create((set, get) => ({
  user: null,
  isAuthenticated: false,
  loading: false,
  error: null,

  login: async (email, password) => {
    set({ loading: true, error: null });
    try {
      const response = await api.post('/auth/login', { email, password });
      const { user } = response.data;
      set({ user, isAuthenticated: true, loading: false });
      return { success: true };
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Login failed' });
      return { success: false, error: error.response?.data?.message || 'Login failed' };
    }
  },

  register: async (email, password) => {
    set({ loading: true, error: null });
    try {
      const response = await api.post('/auth/register', { email, password });
      const { user } = response.data;
      set({ user, isAuthenticated: true, loading: false });
      return { success: true };
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Registration failed' });
      return { success: false, error: error.response?.data?.message || 'Registration failed' };
    }
  },

  logout: async () => {
    try {
      await api.get('/auth/logout');
    } catch (error) {
      console.log('Logout error:', error);
    }
    set({ user: null, isAuthenticated: false, loading: false, error: null });
  },

  checkAuth: async () => {
    set({ loading: true });
    try {
      const response = await api.get('/auth/check');
      set({ user: response.data, isAuthenticated: true, loading: false });
      return true;
    } catch (error) {
      set({ user: null, isAuthenticated: false, loading: false });
      return false;
    }
  },

  clearError: () => set({ error: null }),
}));

export default useAuthStore;