// Documents Service - Camada de dados para documentos

import { mockDocuments, mockDocumentStats } from '../mocks/documentsMock';

const USE_MOCK = true;
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000';

export const documentsService = {
  /**
   * Lista documentos com filtros
   * @param {Object} filters - Filtros (entityType, docType, client, etc)
   */
  async getDocuments(filters = {}) {
    if (USE_MOCK) {
      await new Promise(resolve => setTimeout(resolve, 400));
      let filtered = [...mockDocuments];
      
      if (filters.entityType) {
        filtered = filtered.filter(d => d.entityType === filters.entityType);
      }
      
      if (filters.docType) {
        filtered = filtered.filter(d => d.docType === filters.docType);
      }
      
      if (filters.client) {
        filtered = filtered.filter(d => d.client === filters.client);
      }
      
      return filtered;
    }
    
    const params = new URLSearchParams(filters);
    const response = await fetch(`${API_URL}/api/gr/documents?${params}`);
    if (!response.ok) throw new Error('Erro ao buscar documentos');
    return response.json();
  },

  /**
   * Upload de documento
   * @param {FormData} formData - Dados do formulário com arquivo
   */
  async uploadDocument(formData) {
    if (USE_MOCK) {
      await new Promise(resolve => setTimeout(resolve, 800));
      const newDoc = {
        id: `doc-${Date.now()}`,
        client: formData.get('client'),
        entityType: formData.get('entityType'),
        entityName: formData.get('entityName'),
        docType: formData.get('docType'),
        fileName: formData.get('file')?.name || 'document.pdf',
        filePath: `/uploads/${formData.get('file')?.name}`,
        uploadDate: new Date().toISOString(),
        uploadedBy: 'Current User',
        fileSize: formData.get('file')?.size || 0
      };
      mockDocuments.push(newDoc);
      return { success: true, document: newDoc };
    }
    
    const response = await fetch(`${API_URL}/api/gr/documents`, {
      method: 'POST',
      body: formData
    });
    if (!response.ok) throw new Error('Erro ao fazer upload');
    return response.json();
  },

  /**
   * Exclui documento
   * @param {string} id - ID do documento
   */
  async deleteDocument(id) {
    if (USE_MOCK) {
      await new Promise(resolve => setTimeout(resolve, 300));
      const index = mockDocuments.findIndex(d => d.id === id);
      if (index !== -1) {
        mockDocuments.splice(index, 1);
      }
      return { success: true };
    }
    
    const response = await fetch(`${API_URL}/api/gr/documents/${id}`, {
      method: 'DELETE'
    });
    if (!response.ok) throw new Error('Erro ao excluir documento');
    return response.json();
  },

  /**
   * Retorna estatísticas de documentos
   */
  async getStats() {
    if (USE_MOCK) {
      await new Promise(resolve => setTimeout(resolve, 200));
      return mockDocumentStats;
    }
    
    const response = await fetch(`${API_URL}/api/gr/documents/stats`);
    if (!response.ok) throw new Error('Erro ao buscar estatísticas');
    return response.json();
  }
};
