import ApiService from '@/services/ApiService';
import ApiServiceFile from '@/services/ApiServiceFile';

const base = '/ranch';

export default {
  async catalog() {
    const { data } = await ApiService.get(`${base}/catalog`);
    return data.data;
  },

  async listPastures(activeOnly = true) {
    const { data } = await ApiService.get(`${base}/pastures`, {
      params: { active_only: activeOnly },
    });
    return data.data;
  },

  async createPasture(payload) {
    const { data } = await ApiService.post(`${base}/pastures`, payload);
    return data.data;
  },

  async updatePasture(id, payload) {
    const { data } = await ApiService.put(`${base}/pastures/${id}`, payload);
    return data.data;
  },

  async dashboard() {
    const { data } = await ApiService.get(`${base}/dashboard`);
    return data.data;
  },

  async alertCenter() {
    const { data } = await ApiService.get(`${base}/alerts/center`);
    return data.data;
  },

  async listCattle(params = {}) {
    const { data } = await ApiService.get(`${base}/cattle`, { params });
    return data.data;
  },

  async searchCattle(earTag, extraParams = {}) {
    const { data } = await ApiService.get(`${base}/cattle/search`, {
      params: { ear_tag: earTag, ...extraParams },
    });
    return data.data;
  },

  async getCattle(id) {
    const { data } = await ApiService.get(`${base}/cattle/${id}`);
    return data.data;
  },

  async downloadCattleExpedientePdf(id) {
    const response = await ApiService.get(`${base}/cattle/${id}/expediente/pdf`, {
      responseType: 'blob',
    });
    return response.data;
  },

  async uploadCattlePhoto(id, file) {
    const formData = new FormData();
    formData.append('photo', file);
    const { data } = await ApiServiceFile.post(`${base}/cattle/${id}/photo`, formData);
    return data.data;
  },

  async deleteCattlePhoto(id) {
    const { data } = await ApiServiceFile.delete(`${base}/cattle/${id}/photo`);
    return data.data;
  },

  async createCattle(payload) {
    const { data } = await ApiService.post(`${base}/cattle`, payload);
    return data.data;
  },

  async listCalvings(params = {}) {
    const { data } = await ApiService.get(`${base}/calvings`, { params });
    return data.data;
  },

  async registerCalving(payload) {
    const { data } = await ApiService.post(`${base}/calvings`, payload);
    return data.data;
  },

  async calvingsReport(params = {}) {
    const { data } = await ApiService.get(`${base}/reports/calvings`, { params });
    return data.data;
  },

  async downloadCalvingsReportCsv(params = {}) {
    const response = await ApiService.get(`${base}/reports/calvings/csv`, {
      params,
      responseType: 'blob',
    });
    return response.data;
  },

  async listLocationMovements(params = {}) {
    const { data } = await ApiService.get(`${base}/location-movements`, { params });
    return data.data;
  },

  async moveCattlePasture(cattleId, payload) {
    const { data } = await ApiService.post(`${base}/cattle/${cattleId}/move-pasture`, payload);
    return data.data;
  },

  async updateCattle(id, payload) {
    const { data } = await ApiService.put(`${base}/cattle/${id}`, payload);
    return data.data;
  },

  async deactivateCattle(id, payload) {
    const { data } = await ApiService.post(`${base}/cattle/${id}/deactivate`, payload);
    return data.data;
  },

  async listWeightRecords(params = {}) {
    const { data } = await ApiService.get(`${base}/weight-records`, { params });
    return data.data;
  },

  async listCalvesForWeighing(params = {}) {
    const { data } = await ApiService.get(`${base}/weight-records/calves`, { params });
    return data.data;
  },

  async createWeightRecord(payload) {
    const { data } = await ApiService.post(`${base}/weight-records`, payload);
    return data.data;
  },

  async listFatteningLots(params = {}) {
    const { data } = await ApiService.get(`${base}/fattening-lots`, { params });
    return data.data;
  },

  async getFatteningLot(id) {
    const { data } = await ApiService.get(`${base}/fattening-lots/${id}`);
    return data;
  },

  async createFatteningLot(payload) {
    const { data } = await ApiService.post(`${base}/fattening-lots`, payload);
    return data.data;
  },

  async addAnimalToLot(lotId, payload) {
    const { data } = await ApiService.post(`${base}/fattening-lots/${lotId}/animals`, payload);
    return data.data;
  },

  async closeFatteningLot(lotId, exitWeights) {
    const { data } = await ApiService.post(`${base}/fattening-lots/${lotId}/close`, { exit_weights: exitWeights });
    return data;
  },

  async previewCloseFatteningLot(lotId, exitWeights, pricePerKg = null) {
    const { data } = await ApiService.post(`${base}/fattening-lots/${lotId}/preview-close`, {
      exit_weights: exitWeights,
      ...(pricePerKg != null ? { price_per_kg: pricePerKg } : {}),
    });
    return data.data;
  },

  async closeAndSellFatteningLot(lotId, exitWeights, pricePerKg, saleDate = null) {
    const { data } = await ApiService.post(`${base}/fattening-lots/${lotId}/close-and-sell`, {
      exit_weights: exitWeights,
      price_per_kg: pricePerKg,
      ...(saleDate ? { sale_date: saleDate } : {}),
    });
    return data;
  },

  async getFeedInventory() {
    const { data } = await ApiService.get(`${base}/feed-inventory`);
    return data.data;
  },

  async downloadFatteningLotPdf(lotId) {
    const response = await ApiService.get(`${base}/fattening-lots/${lotId}/pdf`, {
      responseType: 'blob',
    });
    return response.data;
  },

  async updateFatteningLot(lotId, payload) {
    const { data } = await ApiService.put(`${base}/fattening-lots/${lotId}`, payload);
    return data.data;
  },

  async materialTypes(params = {}) {
    const { data } = await ApiService.get(`${base}/material-types`, { params });
    return data.data;
  },

  async createMaterialType(payload) {
    const { data } = await ApiService.post(`${base}/material-types`, payload);
    return data.data;
  },

  async updateMaterialType(id, payload) {
    const { data } = await ApiService.put(`${base}/material-types/${id}`, payload);
    return data.data;
  },

  async listFeedCatalog() {
    return this.materialTypes({ category: 'feed_supplements', active_only: false });
  },

  async listFeedIntakes(lotId, params = {}) {
    const { data } = await ApiService.get(`${base}/fattening-lots/${lotId}/feed-intakes`, { params });
    return data;
  },

  async createFeedIntake(lotId, payload) {
    const { data } = await ApiService.post(`${base}/fattening-lots/${lotId}/feed-intakes`, payload);
    return data;
  },

  async updateFeedIntake(lotId, intakeId, payload) {
    const { data } = await ApiService.put(`${base}/fattening-lots/${lotId}/feed-intakes/${intakeId}`, payload);
    return data;
  },

  async deleteFeedIntake(lotId, intakeId) {
    const { data } = await ApiService.delete(`${base}/fattening-lots/${lotId}/feed-intakes/${intakeId}`);
    return data;
  },

  async listExpenses(params = {}) {
    const { data } = await ApiService.get(`${base}/expenses`, { params });
    return data.data;
  },

  async listAllExpenses(params = {}) {
    const { data } = await ApiService.get(`${base}/expenses`, {
      params: { ...params, all: 1 },
    });
    const payload = data?.data;
    if (Array.isArray(payload)) return payload;
    if (Array.isArray(payload?.data)) return payload.data;
    return [];
  },

  async createExpense(payload) {
    const { data } = await ApiService.post(`${base}/expenses`, payload);
    return data.data;
  },

  async periodBalance(from, to) {
    const { data } = await ApiService.get(`${base}/reports/period-balance`, { params: { from, to } });
    return data.data;
  },

  async downloadPeriodBalanceCsv(from, to) {
    const response = await ApiService.get(`${base}/reports/period-balance/csv`, {
      params: { from, to },
      responseType: 'blob',
    });
    return response.data;
  },

  async sendWeightAlertEmail(payload = {}) {
    const { data } = await ApiService.post(`${base}/notifications/weight-alerts`, payload);
    return data.data;
  },

  async sendOpenLotsGdpAlertEmail(payload = {}) {
    const { data } = await ApiService.post(`${base}/notifications/open-lots-gdp-alerts`, payload);
    return data.data;
  },

  async sendCalvingReportEmail(payload = {}) {
    const { data } = await ApiService.post(`${base}/notifications/calving-report`, payload);
    return data.data;
  },

  async sendCostAlertEmail(payload = {}) {
    const { data } = await ApiService.post(`${base}/notifications/cost-alerts`, payload);
    return data.data;
  },

  async weightPerformance(params = {}) {
    const { data } = await ApiService.get(`${base}/reports/weight-performance`, { params });
    return data.data;
  },

  async motherPerformance(params = {}) {
    const { data } = await ApiService.get(`${base}/reports/mother-performance`, { params });
    return data.data;
  },

  async healthCatalog() {
    const { data } = await ApiService.get(`${base}/health-events/catalog`);
    return data.data;
  },

  async listHealthEvents(params = {}) {
    const { data } = await ApiService.get(`${base}/health-events`, { params });
    return data.data;
  },

  async createHealthEvent(payload) {
    const { data } = await ApiService.post(`${base}/health-events`, payload);
    return data.data;
  },

  async healthSummary(params = {}) {
    const { data } = await ApiService.get(`${base}/health-events/summary`, { params });
    return data.data;
  },

  async animalProfitability(params = {}) {
    const { data } = await ApiService.get(`${base}/reports/animal-profitability`, { params });
    return data.data;
  },

  async downloadAnimalProfitabilityCsv(params = {}) {
    const response = await ApiService.get(`${base}/reports/animal-profitability/csv`, {
      params,
      responseType: 'blob',
    });
    return response.data;
  },

  async openLotsGdpAlerts(params = {}) {
    const { data } = await ApiService.get(`${base}/reports/open-lots-gdp-alerts`, { params });
    return data.data;
  },

  async openLotsProjection() {
    const { data } = await ApiService.get(`${base}/reports/open-lots-projection`);
    return data.data;
  },

  async downloadOpenLotsProjectionCsv() {
    const response = await ApiService.get(`${base}/reports/open-lots-projection/csv`, {
      responseType: 'blob',
    });
    return response.data;
  },

  async inventoryReport(params = {}) {
    const { data } = await ApiService.get(`${base}/reports/inventory`, { params });
    return data.data;
  },

  async downloadInventoryReportCsv(params = {}) {
    const response = await ApiService.get(`${base}/reports/inventory/csv`, {
      params,
      responseType: 'blob',
    });
    return response.data;
  },

  async closedLotsRanking(params = {}) {
    const { data } = await ApiService.get(`${base}/reports/closed-lots-ranking`, { params });
    return data.data;
  },

  async downloadClosedLotsRankingCsv(params = {}) {
    const response = await ApiService.get(`${base}/reports/closed-lots-ranking/csv`, {
      params,
      responseType: 'blob',
    });
    return response.data;
  },

  async downloadAnimalProfitabilityPdf(params = {}) {
    const response = await ApiService.get(`${base}/reports/animal-profitability/pdf`, {
      params,
      responseType: 'blob',
    });
    return response.data;
  },

  async activeCostAlerts(params = {}) {
    const { data } = await ApiService.get(`${base}/reports/active-cost-alerts`, { params });
    return data.data;
  },

  async downloadPeriodBalancePdf(from, to) {
    const response = await ApiService.get(`${base}/reports/period-balance/pdf`, {
      params: { from, to },
      responseType: 'blob',
    });
    return response.data;
  },

  async listDatabaseBackups() {
    const { data } = await ApiService.get(`${base}/admin/database-backup`);
    return data.data;
  },

  async downloadDatabaseBackup({ fresh = true, file = null } = {}) {
    const response = await ApiService.get(`${base}/admin/database-backup/download`, {
      params: { fresh: fresh ? 1 : undefined, file: file || undefined },
      responseType: 'blob',
    });
    return response.data;
  },
};
