// Spreadsheets Service - Camada de dados para planilhas

import { mockSpreadsheetData, mockSpreadsheetStats } from '../mocks/spreadsheetsMock';

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

export const spreadsheetsService = {
  /**
   * Lista dados de planilhas
   * @param {Object} filters - Filtros (clientId, archived, etc)
   */
  async getSpreadsheetData(filters = {}) {
    if (USE_MOCK) {
      await new Promise(resolve => setTimeout(resolve, 400));
      let filtered = [...mockSpreadsheetData];
      
      if (filters.clientId) {
        filtered = filtered.filter(r => r.clientId === filters.clientId);
      }
      
      if (filters.archived !== undefined) {
        filtered = filtered.filter(r => r.archived === filters.archived);
      }
      
      return filtered;
    }
    
    const params = new URLSearchParams(filters);
    const response = await fetch(`${API_URL}/api/gr/spreadsheets?${params}`);
    if (!response.ok) throw new Error('Erro ao buscar dados');
    return response.json();
  },

  /**
   * Importa dados de planilha Excel
   * @param {Object} data - Dados a importar
   */
  async importSpreadsheet(data) {
    if (USE_MOCK) {
      await new Promise(resolve => setTimeout(resolve, 1000));
      const newRows = data.rows.map((row, index) => ({
        id: `row-${Date.now()}-${index}`,
        clientId: data.clientId,
        rowId: mockSpreadsheetData.length + index + 1,
        data: row,
        archived: false,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }));
      mockSpreadsheetData.push(...newRows);
      return { success: true, imported: newRows.length, rows: newRows };
    }
    
    const response = await fetch(`${API_URL}/api/gr/spreadsheets/import`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    });
    if (!response.ok) throw new Error('Erro ao importar planilha');
    return response.json();
  },

  /**
   * Arquiva registro
   * @param {string} id - ID do registro
   */
  async archiveRow(id) {
    if (USE_MOCK) {
      await new Promise(resolve => setTimeout(resolve, 300));
      const row = mockSpreadsheetData.find(r => r.id === id);
      if (row) {
        row.archived = true;
        row.updatedAt = new Date().toISOString();
      }
      return { success: true, row };
    }
    
    const response = await fetch(`${API_URL}/api/gr/spreadsheets/${id}/archive`, {
      method: 'PATCH'
    });
    if (!response.ok) throw new Error('Erro ao arquivar');
    return response.json();
  },

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