import axios from '../utils/api';
import { User, UserFormData } from '../types/auth';

export const userService = {
  getUsers: async (): Promise<User[]> => {
    try {
      const response = await axios.get('/users');
      return response.data;
    } catch (error) {
      console.error('Error fetching users:', error);
      throw new Error('Failed to fetch users');
    }
  },

  createUser: async (userData: UserFormData): Promise<User> => {
    try {
      const response = await axios.post('/users', userData);
      return response.data;
    } catch (error) {
      console.error('Error creating user:', error);
      throw new Error('Failed to create user');
    }
  },

  updateUser: async (userId: string, userData: Partial<UserFormData>): Promise<User> => {
    try {
      const response = await axios.put(`/users/${userId}`, userData);
      return response.data;
    } catch (error) {
      console.error('Error updating user:', error);
      throw new Error('Failed to update user');
    }
  },

  updateUserPermissions: async (userId: string, permissions: User['permissions']): Promise<User> => {
    try {
      const response = await axios.put(`/users/${userId}/permissions`, { permissions });
      return response.data;
    } catch (error) {
      console.error('Error updating user permissions:', error);
      throw new Error('Failed to update user permissions');
    }
  },

  deleteUser: async (userId: string): Promise<void> => {
    try {
      await axios.delete(`/users/${userId}`);
    } catch (error) {
      console.error('Error deleting user:', error);
      throw new Error('Failed to delete user');
    }
  }
};