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

export const apiRequestService = (contextPath = '/') => {

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

  return {
    async createAPIRequest(collectionId, apiData) {
      const response = await fetch(`${contextPath}mgmt/collections/${collectionId}/apis/save.do`, {
        method: 'POST',
        headers,
        body: JSON.stringify(apiData)
      });

      if (!response.ok) throw new Error('Failed to create API request');

      const newApiId = await response.json();
      return {
        ...apiData,
        id: newApiId,
        collectionId,
        responseModel: {
          status: 0,
          time: 0,
          size: 0,
          headers: [],
          body: ''
        }
      };
    },

    async updateAPIRequest(apiRequest) {
      const response = await fetch(`${contextPath}mgmt/collections/${apiRequest.collectionId}/apis/save.do`, {
        method: 'POST',
        headers,
        body: JSON.stringify(apiRequest)
      });

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

    async deleteAPIRequest(collectionId, apiId) {
      const response = await fetch(`${contextPath}mgmt/collections/${collectionId}/apis/delete.do`, {
        method: 'POST',
        headers,
        body: JSON.stringify({ id: apiId })
      });

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