/**
 * Workspace Conciliação API - Service for handling API requests
 * 
 * Endpoints:
 * - Categories: /api/categorias/apresentar
 * - Rules: /api/regras/apresentar
 * - Statement: /api/extrato/apresentar
 * - Caixinhas: /api/caixinhas/apresentar
 */

import api from './api';

const WorkspaceConciliacaoAPI = {
  baseUrl: "https://dev.workspace.itguys.com.br",

  getHeaders: async function () {
    // getTokenForModule agora é async
    const token = await getTokenForModule('workspace');
    const fallbackToken = !token ? localStorage.getItem('x-access-token') : null;
    const finalToken = token || fallbackToken;
    const setor = getSetorForModule('workspace') || 'Workspace';
    
    if (!finalToken && isDevelopment()) {
      secureLog("WorkspaceConciliacaoAPI: No token found for workspace module.");
    }
    
    return {
      "Content-Type": "application/json",
      "x-access-token": finalToken || "",
      "x-setor": setor || ""
    };
  },

  fetchCategories: async function () {
    try {
      const response = await api.get('/categorias/apresentar');
      if (!response.data) throw new Error(`Status ${response.status}`);
      const raw = response.data;
      let data = raw?.dados ?? raw?.Base_Dados_API ?? raw;
      if (!Array.isArray(data)) {
        data = Object.values(data || {});
      }
      return data.map(item => ({
        id: item.idcategoria || item.id || 0,
        name: item.categoria || item.name || ''
      }));
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error fetching categories", error);
      return [];
    }
  },

  fetchRules: async function () {
    try {
      const response = await api.get('/regras/apresentar');
      if (!response.data) throw new Error(`Status ${response.status}`);
      const raw = response.data;
      let data = raw?.dados ?? raw?.Base_Dados_API ?? raw;
      if (!Array.isArray(data)) {
        data = Object.values(data || {});
      }
      return data.map(item => ({
        id: item.idregras_financeiro || item.id || 0,
        name: item.regra || item.name || '',
        condition: item.condicional || item.condition || '',
        categoryId: item.categoria || item.categoryId || null,
        caixinha: item.caixinha || null,
        beneficiario: item.beneficiario_pagador || item.beneficiario || null
      }));
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error fetching rules", error);
      return [];
    }
  },

  fetchCaixinhas: async function () {
    try {
      const response = await api.get('/caixinhas/apresentar');
      if (!response.data) throw new Error(`Status ${response.status}`);
      const raw = response.data;
      let data = raw?.dados ?? raw?.Base_Dados_API ?? raw;
      if (!Array.isArray(data)) {
        data = Object.values(data || {});
      }
      return data.map(item => ({
        id: item.idcaixinhas_financeiro || item.id || 0,
        name: item.caixinha || item.name || ''
      }));
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error fetching caixinhas", error);
      return [];
    }
  },

  createCategory: async function (payload) {
    try {
      const response = await api.post('/categorias/create', payload);
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error creating category", error);
      throw error;
    }
  },

  editCategory: async function (payload) {
    try {
      const response = await api.post('/categorias/edit', payload);
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error editing category", error);
      throw error;
    }
  },

  deleteCategory: async function (id) {
    try {
      const response = await api.delete('/categorias/delete', {
        data: { idcategoria: id }
      });
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error deleting category", error);
      throw error;
    }
  },

  createRule: async function (payload) {
    try {
      const response = await api.post('/regra/create', payload);
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error creating rule", error);
      throw error;
    }
  },

  editRule: async function (payload) {
    try {
      const response = await api.post('/regras/edit', payload);
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error editing rule", error);
      throw error;
    }
  },

  deleteRule: async function (id) {
    try {
      const response = await api.delete('/regras/delete', {
        data: { idregras_financeiro: id }
      });
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error deleting rule", error);
      throw error;
    }
  },

  createCaixinha: async function (payload) {
    try {
      const response = await api.post('/caixinha/create', payload);
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error creating caixinha", error);
      throw error;
    }
  },

  editCaixinha: async function (payload) {
    try {
      const response = await api.post('/caixinha/edit', payload);
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error editing caixinha", error);
      throw error;
    }
  },

  deleteCaixinha: async function (id) {
    try {
      const response = await api.delete('/caixinhas/delete', {
        data: { idcaixinhas_financeiro: id }
      });
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error deleting caixinha", error);
      throw error;
    }
  },

  // Manual Reconciliation Update Endpoints
  // Note: Backend uses POST for "inserir" endpoints (not PUT/UPDATE)
  updateTransactionCategory: async function (idExtrato, idCategoria) {
    try {
      const response = await api.post('/categoria_extrato/inserir', {
        idextrato: idExtrato,
        categoria: idCategoria
      });
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error updating transaction category", error);
      throw error;
    }
  },

  updateTransactionBeneficiary: async function (idExtrato, beneficiary) {
    try {
      const response = await api.post('/beneficiario_pagador/inserir', {
        idextrato: idExtrato,
        beneficiario_pagador: beneficiary
      });
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error updating transaction beneficiary", error);
      throw error;
    }
  },

  updateTransactionBox: async function (idExtrato, idCaixinha) {
    try {
      const response = await api.post('/caixinha_extrato/inserir', {
        idextrato: idExtrato,
        caixinha: idCaixinha
      });
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error updating transaction box", error);
      throw error;
    }
  },

  // Automated Reconciliation Update Endpoint
  updateTransactionRule: async function (idExtrato, updateObj) {
    try {
      const response = await api.post('/regra_categoria/edit', {
        idextrato: idExtrato,
        ...updateObj
      });
      if (!response.data) throw new Error(`Status ${response.status}`);
      return response.data;
    } catch (error) {
      console.error("WorkspaceConciliacaoAPI: Error updating transaction rule", error);
      throw error;
    }
  }
};

export default WorkspaceConciliacaoAPI;
