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

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

  return {
    async loadTests() {
      const response = await fetch(`${contextPath}mgmt/load_test/list.do`, { headers });
      if (!response.ok) throw new Error('Failed to fetch load tests');
      return await response.json();
    },

    async createTest(testName) {
      const response = await fetch(`${contextPath}mgmt/load_test/create.do`, {
        method: 'POST',
        headers,
        body: JSON.stringify({ name: testName })
      });

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

    async updateTest(test) {
      const response = await fetch(`${contextPath}mgmt/load_test/update.do`, {
        method: 'POST',
        headers,
        body: JSON.stringify(test)
      });

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

    async deleteTest(testId) {
      const response = await fetch(`${contextPath}mgmt/load_test/delete.do`, {
        method: 'POST',
        headers,
        body: JSON.stringify({ id: testId })
      });

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

    async startTest(test) {
      const response = await fetch(`${contextPath}startLoadTest`, {
        method: 'POST',
        headers,
        body: JSON.stringify(test)
      });

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

    async stopTest(test) {
      const response = await fetch(`${contextPath}stopLoadTest`, {
        method: 'POST',
        headers,
        body: JSON.stringify(test)
      });

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