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;
    },

    async getMockRoutes(params = { name: '', page: 0 }) {
      const searchParams = new URLSearchParams();
      if (params.name) searchParams.append('name', params.name);
      if (typeof params.page !== 'undefined') searchParams.append('page', params.page.toString());

      const queryString = searchParams.toString();
      const url = `${contextPath}api/mock-routes${queryString ? `?${queryString}` : ''}`;

      const response = await fetch(url, { headers });
      if (!response.ok) throw new Error('Failed to fetch mock routes');
      return response.json();
    },

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

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

    async createMockRoute(mockRoute) {
      const response = await fetch(`${contextPath}api/mock-routes`, {
        method: 'POST',
        headers,
        body: JSON.stringify(mockRoute)
      });

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

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

      if (!response.ok) throw new Error('Failed to update mock route');
      return response.json();
    }

  };
};
