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

export const serverService = () => {
  return {
    async loadServers() {
      const response = await fetch('/servers/list.do');
      if (!response.ok) throw new Error(`Failed to fetch servers: ${response.statusText}`);

      const data = await response.json();
      if (!Array.isArray(data)) throw new Error('Invalid server data format');

      return data.map(server => ({
        id: server?.id || crypto.randomUUID(),
        name: server?.name || 'Unnamed Server',
        basePath: server?.basePath || '',
        environment: server?.environment || 'unknown'
      }));
    },

    async loadServerList(params = { page: 0, name: '' }) {
      const searchParams = new URLSearchParams({
        page: params.page,
        size: 10,
        ...(params.name && { name: params.name })
      });

      const response = await fetch(`/servers?${searchParams}`);
      if (!response.ok) throw new Error('Failed to load servers');
      return response.json();
    },

    async createServer(server) {
      const response = await fetch('/servers', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-XSRF-TOKEN': getCSRFToken()
        },
        body: JSON.stringify(server)
      });

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

    async updateServer(id, server) {
      const response = await fetch(`/servers/update/${id}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-XSRF-TOKEN': getCSRFToken()
        },
        body: JSON.stringify(server)
      });

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

    async deleteServers(ids) {
      const response = await fetch('/servers/delete', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-XSRF-TOKEN': getCSRFToken()
        },
        body: JSON.stringify(ids)
      });

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