// Checklist Service - Camada de dados para checklist e manutenção

import { mockVehicles, mockMaintenanceLogs, mockChecklistStats } from '../mocks/checklistMock';

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

export const checklistService = {
  /**
   * Lista veículos com status de checklist
   * @param {Object} filters - Filtros (client, status, etc)
   */
  async getVehicles(filters = {}) {
    if (USE_MOCK) {
      await new Promise(resolve => setTimeout(resolve, 400));
      let filtered = [...mockVehicles];
      
      if (filters.client) {
        filtered = filtered.filter(v => v.client === filters.client);
      }
      
      if (filters.status) {
        filtered = filtered.filter(v => v.status === filters.status);
      }
      
      return filtered;
    }
    
    const params = new URLSearchParams(filters);
    const response = await fetch(`${API_URL}/api/gr/checklist/vehicles?${params}`);
    if (!response.ok) throw new Error('Erro ao buscar veículos');
    return response.json();
  },

  /**
   * Renova checklist de um veículo (+30 dias)
   * @param {string} id - ID do veículo
   */
  async renewChecklist(id) {
    if (USE_MOCK) {
      await new Promise(resolve => setTimeout(resolve, 500));
      const vehicle = mockVehicles.find(v => v.id === id);
      if (vehicle) {
        const currentExpiry = new Date(vehicle.checklistExpiry);
        const newExpiry = new Date(currentExpiry.setDate(currentExpiry.getDate() + 30));
        vehicle.checklistExpiry = newExpiry.toISOString().split('T')[0];
        vehicle.lastRenewal = new Date().toISOString();
        vehicle.status = 'VALID';
      }
      return { success: true, vehicle };
    }
    
    const response = await fetch(`${API_URL}/api/gr/checklist/renew/${id}`, {
      method: 'POST'
    });
    if (!response.ok) throw new Error('Erro ao renovar checklist');
    return response.json();
  },

  /**
   * Lista ordens de serviço
   * @param {Object} filters - Filtros (vehicleId, status, etc)
   */
  async getMaintenanceOrders(filters = {}) {
    if (USE_MOCK) {
      await new Promise(resolve => setTimeout(resolve, 300));
      let filtered = [...mockMaintenanceLogs];
      
      if (filters.vehicleId) {
        filtered = filtered.filter(os => os.vehicleId === filters.vehicleId);
      }
      
      if (filters.status) {
        filtered = filtered.filter(os => os.status === filters.status);
      }
      
      return filtered;
    }
    
    const params = new URLSearchParams(filters);
    const response = await fetch(`${API_URL}/api/gr/maintenance/orders?${params}`);
    if (!response.ok) throw new Error('Erro ao buscar OS');
    return response.json();
  },

  /**
   * Cria nova ordem de serviço
   * @param {Object} data - Dados da OS
   */
  async createMaintenanceOrder(data) {
    if (USE_MOCK) {
      await new Promise(resolve => setTimeout(resolve, 400));
      const newOS = {
        id: `os-${Date.now()}`,
        ...data,
        osNumber: `OS-${new Date().getFullYear()}-${mockMaintenanceLogs.length + 1}`,
        status: 'ABERTO',
        createdAt: new Date().toISOString(),
        resolvedAt: null,
        resolvedBy: null
      };
      mockMaintenanceLogs.push(newOS);
      return { success: true, order: newOS };
    }
    
    const response = await fetch(`${API_URL}/api/gr/maintenance/orders`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    });
    if (!response.ok) throw new Error('Erro ao criar OS');
    return response.json();
  },

  /**
   * Atualiza status de uma OS
   * @param {string} id - ID da OS
   * @param {string} status - Novo status
   */
  async updateOrderStatus(id, status) {
    if (USE_MOCK) {
      await new Promise(resolve => setTimeout(resolve, 300));
      const order = mockMaintenanceLogs.find(os => os.id === id);
      if (order) {
        order.status = status;
        if (status === 'RESOLVIDO') {
          order.resolvedAt = new Date().toISOString();
        }
      }
      return { success: true, order };
    }
    
    const response = await fetch(`${API_URL}/api/gr/maintenance/orders/${id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status })
    });
    if (!response.ok) throw new Error('Erro ao atualizar OS');
    return response.json();
  },

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