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

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

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

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

    async createQueue(queue) {
      const response = await fetch(`${contextPath}api/queue-handlers`, {
        method: 'POST',
        headers,
        body: JSON.stringify(queue)
      });

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

    async updateQueue(id, queue) {
      const response = await fetch(`${contextPath}api/queue-handlers/update/${id}`, {
        method: 'POST',
        headers,
        body: JSON.stringify(queue)
      });

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

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

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

    async startQueue(id) {
      const response = await fetch(`${contextPath}api/queue-handlers/${id}/start`, {
        method: 'POST',
        headers
      });

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

    async stopQueue(id) {
      const response = await fetch(`${contextPath}api/queue-handlers/${id}/stop`, {
        method: 'POST',
        headers
      });

      if (!response.ok) throw new Error('Failed to stop queue');
    }
  };
};
