import { getCSRFToken } from '@/services/token.js';

export const userService = (contextPath = '/') => {
  const headers = {
    'Content-Type': 'application/json',
    'X-XSRF-TOKEN': getCSRFToken()
  };

  return {
    async findAll(params = { page: 0 }) {
      const searchParams = new URLSearchParams({
        page: params.page,
        size: 10,
        ...(params.username && { username: params.username })
      });

      const response = await fetch(`${contextPath}api/users?${searchParams}`);
      if (!response.ok) throw new Error('Failed to fetch users');
      return await response.json();
    },

    async create(user) {
      const response = await fetch(`${contextPath}api/users`, {
        method: 'POST',
        headers,
        body: JSON.stringify(user)
      });

      if (!response.ok) throw new Error('Failed to create user');
      return await response.json();
    },

    async update(userId, user) {
      const response = await fetch(`${contextPath}api/users/update/${userId}`, {
        method: 'POST',
        headers,
        body: JSON.stringify(user)
      });

      if (!response.ok) throw new Error('Failed to update user');
      return await response.json();
    },

    async deleteUsers(ids) {
      const response = await fetch(`${contextPath}api/users/delete`, {
        method: 'POST',
        headers,
        body: JSON.stringify(ids)
      });

      if (!response.ok) throw new Error('Failed to delete users');
    },

    async resetPassword(userId, passwordData) {
      const response = await fetch(`${contextPath}api/users/reset-password/${userId}`, {
        method: 'POST',
        headers,
        body: JSON.stringify(passwordData)
      });

      if (!response.ok) throw new Error('Failed to reset password');
    }
  };
};
