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

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

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

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

      const data = await response.json();
      return data.map(collection => ({
        ...collection,
        apis: collection.apis?.map(api => ({...api, collectionId: collection.id})) || []
      }));
    },

    async createCollection(name) {
      await fetch(`${contextPath}mgmt/collections/create.do`, {
        method: 'POST',
        headers,
        body: JSON.stringify({ name })
      });
    },

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

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

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

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