import api from '@/services/api';
import { handleRequest } from '@/services/serviceUtils';

// Endpoints definidos pelo usuário
const ENDPOINTS = {
  VEHICLES: '/cadastro_frota',
  MAINTENANCE: '/manutencao_frota',
  AVAILABILITY: '/disponibilidade_frota',
  MOKI: '/moki_frota',
  STATUS: '/status_frota',
  MONITORING: '/monitoramento_frota',
  CLAIMS: '/sinistro_devolucao_venda_frota',
  WORKSHOPS: '/oficinas_frota',
  AUTH: '/auth_monitoramento'
};

export const prafrotService = {
  // --- Autenticação ---
  login: (credentials) => handleRequest({
    apiFn: async () => {
      const { data } = await api.post(ENDPOINTS.AUTH, credentials);
      return data;
    }
  }),

  // --- Cadastro de Frota (Veículos) ---
  getVehicles: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get(`${ENDPOINTS.VEHICLES}/apresentar`);
      return data;
    }
  }),
  createVehicle: (payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.post(ENDPOINTS.VEHICLES, payload);
      return data;
    }
  }),
  updateVehicle: (id, payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.VEHICLES}/${id}`, payload);
      return data;
    }
  }),
  deleteVehicle: (id) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.VEHICLES}/delete/${id}`);
      return data;
    }
  }),

  // --- Manutenção ---
  getMaintenance: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get(`${ENDPOINTS.MAINTENANCE}/apresentar`);
      return data;
    }
  }),
  calcularDifOrcamento: (orcamento_inicial, orcamento_final) => handleRequest({
    apiFn: async () => {
      const { data } = await api.post(`${ENDPOINTS.MAINTENANCE}/calcular_dif_orcamento`, {
        orcamento_inicial,
        orcamento_final
      });
      return data;
    }
  }),
  createMaintenance: (payload, files = null) => handleRequest({
    apiFn: async () => {
      // Envia previsao_entrega diretamente
      const body = { ...payload };
      if (files && (files.pdf_orcamento || files.nota_fiscal)) {
        const form = new FormData();
        form.append('data_json', JSON.stringify(body));
        if (files.pdf_orcamento instanceof File) form.append('pdf_orcamento', files.pdf_orcamento);
        if (files.nota_fiscal instanceof File) form.append('nota_fiscal', files.nota_fiscal);
        const { data } = await api.post(ENDPOINTS.MAINTENANCE, form, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });
        return data;
      }
      const { data } = await api.post(ENDPOINTS.MAINTENANCE, body);
      return data;
    }
  }),
  updateMaintenance: (id, payload, files = null) => handleRequest({
    apiFn: async () => {
      // Envia previsao_entrega diretamente (o backend deve estar atualizado ou o frontend deve padronizar)
      const body = { ...payload };
      if (files && (files.pdf_orcamento || files.nota_fiscal)) {
        const form = new FormData();
        form.append('data_json', JSON.stringify(body));
        if (files.pdf_orcamento instanceof File) form.append('pdf_orcamento', files.pdf_orcamento);
        if (files.nota_fiscal instanceof File) form.append('nota_fiscal', files.nota_fiscal);
        const { data } = await api.put(`${ENDPOINTS.MAINTENANCE}/${id}`, form, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });
        return data;
      }
      const { data } = await api.put(`${ENDPOINTS.MAINTENANCE}/${id}`, body);
      return data;
    }
  }),
  updateMaintenanceBatch: (ids, status) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.MAINTENANCE}/edit/em_lote`, { ids, status });
      return data;
    }
  }),
  deleteMaintenance: (id) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.MAINTENANCE}/delete/${id}`);
      return data;
    }
  }),
  // Fechar/Abrir manutenção
  fecharManutencao: (id) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.MAINTENANCE}/fechar_manutencao/${id}`);
      return data;
    }
  }),
  abrirManutencao: (id) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.MAINTENANCE}/abrir_manutencao/${id}`);
      return data;
    }
  }),
  getAbertoFechado: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get(`${ENDPOINTS.MAINTENANCE}/aberto_fechado/apresentar`);
      return data;
    }
  }),
  // Histórico de manutenção
  getHistoricoCompleto: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get('/historico/completo');
      return data;
    }
  }),
  getHistoricoDetalhado: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get('/historico/detalhado');
      return data;
    }
  }),
  getHistoricoResumido: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get('/historico/resumido');
      return data;
    }
  }),
  getHistoricoEstatisticas: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get('/historico/estatisticas');
      return data;
    }
  }),
  getHistoricoPeriodo: (params) => handleRequest({
    apiFn: async () => {
      const { data } = await api.get('/historico/periodo', { params });
      return data;
    }
  }),
  getHistoricoTop: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get('/historico/top');
      return data;
    }
  }),
  getHistoricoPorPlaca: (placa) => handleRequest({
    apiFn: async () => {
      const { data } = await api.get(`/historico/placa/${placa}`);
      return data;
    }
  }),

  // --- Disponibilidade ---
  getAvailability: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get(`${ENDPOINTS.AVAILABILITY}/apresentar`);
      return data;
    }
  }),
  createAvailability: (payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.post(ENDPOINTS.AVAILABILITY, payload);
      return data;
    }
  }),
  updateAvailability: (id, payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.AVAILABILITY}/${id}`, payload);
      return data;
    }
  }),
  deleteAvailability: (id) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.AVAILABILITY}/delete/${id}`);
      return data;
    }
  }),

  // --- Moki (Checklists) ---
  getMoki: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get(`${ENDPOINTS.MOKI}/apresentar`);
      return data;
    }
  }),
  createMoki: (payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.post(ENDPOINTS.MOKI, payload);
      return data;
    }
  }),
  updateMoki: (id, payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.MOKI}/${id}`, payload);
      return data;
    }
  }),
  deleteMoki: (id) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.MOKI}/delete/${id}`);
      return data;
    }
  }),

  // --- Status Frota ---
  getStatus: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get(`${ENDPOINTS.STATUS}/apresentar`);
      return data;
    }
  }),
  createStatus: (payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.post(ENDPOINTS.STATUS, payload);
      return data;
    }
  }),
  updateStatus: (id, payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.STATUS}/${id}`, payload);
      return data;
    }
  }),
  updateStatusBatch: (ids, statusFrota) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.STATUS}/edit/em_lote`, { ids, status_frota: statusFrota });
      return data;
    }
  }),
  deleteStatus: (id) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.STATUS}/delete/${id}`);
      return data;
    }
  }),

  // --- Monitoramento ---
  getMonitoring: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get(`${ENDPOINTS.MONITORING}/apresentar`);
      return data;
    }
  }),
  createMonitoring: (payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.post(ENDPOINTS.MONITORING, payload);
      return data;
    }
  }),
  updateMonitoring: (id, payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.MONITORING}/${id}`, payload);
      return data;
    }
  }),
  deleteMonitoring: (id) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.MONITORING}/delete/${id}`);
      return data;
    }
  }),

  // --- Sinistro / Devolução ---
  getClaims: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get(`${ENDPOINTS.CLAIMS}/apresentar`);
      return data;
    }
  }),
  createClaims: (payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.post(ENDPOINTS.CLAIMS, payload);
      return data;
    }
  }),
  updateClaims: (id, payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.CLAIMS}/${id}`, payload);
      return data;
    }
  }),
  deleteClaim: (id) => handleRequest({
    apiFn: async () => {
      // Usando a rota específica fornecida pelo usuário para exclusão de sinistro
      const { data } = await api.put(`/sinistro_frota/delete/${id}`);
      return data;
    }
  }),

  // --- Oficinas ---
  getWorkshops: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get(`${ENDPOINTS.WORKSHOPS}/apresentar`);
      return data;
    }
  }),
  createWorkshop: (payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.post(ENDPOINTS.WORKSHOPS, payload);
      return data;
    }
  }),
  updateWorkshop: (id, payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.WORKSHOPS}/${id}`, payload);
      return data;
    }
  }),
  deleteWorkshop: (id) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`${ENDPOINTS.WORKSHOPS}/delete/${id}`);
      return data;
    }
  }),

  // --- Motoristas (Drivers) ---
  getDrivers: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get('/motoristas/listagem');
      return data;
    }
  }),

  // --- Listas de Configuração (Config Lists) ---
  getListasConfig: () => handleRequest({
    apiFn: async () => {
      const { data } = await api.get('/listas_frota/config');
      return data;
    }
  }),

  getListasByRoute: (route) => handleRequest({
    apiFn: async () => {
      const { data } = await api.get(`/listas_frota/${route}`);
      return data;
    }
  }),

  createLista: (route, payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.post(`/listas_frota/${route}`, payload);
      return data;
    }
  }),

  updateLista: (route, id, payload) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put(`/listas_frota/${route}/${id}`, payload);
      return data;
    }
  }),

  deleteLista: (route, id) => handleRequest({
    apiFn: async () => {
      const { data } = await api.delete(`/listas_frota/${route}/${id}`);
      return data;
    }
  }),

  // --- Update Vehicle Status (Inline Edit) ---
  updateVehicleStatus: (idVehicle, statusFrota) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put('/status_frota/edit/em_lote', {
        ids: [idVehicle],
        status_frota: statusFrota
      });
      return data;
    }
  }),

  // --- Update Status Batch (Bulk Edit) ---
  updateStatusBatch: (ids, statusFrota) => handleRequest({
    apiFn: async () => {
      const { data } = await api.put('/status_frota/edit/em_lote', {
        ids,
        status_frota: statusFrota
      });
      return data;
    }
  })
};



