import { defineStore } from "pinia";
import { ref } from "vue";
import api from "@reports/services/api";

export const useTreasuryStore = defineStore("treasury", () => {
  const registers = ref([]);
  const isLoading = ref(false);
  const error = ref(null);
  const pagination = ref({
    page: 0,
    rows: 50,
    totalRecords: 0,
  });
  const totals = ref({
    total_incasari: 0,
    total_plati: 0,
    // Totaluri din TOATE înregistrările filtrate (nu doar pagina curentă)
    sold_precedent_all: 0,
    total_incasari_all: 0,
    total_plati_all: 0,
    sold_final_all: 0,
  });
  const accountingPeriod = ref({ an: null, luna: null });

  const loadBankCashRegister = async (companyId, filters = {}) => {
    isLoading.value = true;
    error.value = null;

    try {
      const params = {
        company: companyId,
        page: pagination.value.page + 1,
        page_size: pagination.value.rows,
        ...filters,
      };

      const response = await api.get("/treasury/bank-cash-register", {
        params,
      });

      registers.value = response.data.registers || [];
      pagination.value.totalRecords = response.data.total_count || 0;
      totals.value = {
        total_incasari: response.data.total_incasari,
        total_plati: response.data.total_plati,
        // Totaluri din TOATE înregistrările filtrate (nu doar pagina curentă)
        sold_precedent_all: response.data.sold_precedent_all || 0,
        total_incasari_all: response.data.total_incasari_all || 0,
        total_plati_all: response.data.total_plati_all || 0,
        sold_final_all: response.data.sold_final_all || 0,
      };

      // Store accounting period if available
      if (response.data.accounting_period) {
        accountingPeriod.value = response.data.accounting_period;
      }

      return { success: true };
    } catch (err) {
      error.value = err.response?.data?.detail || "Failed to load register";
      console.error("Failed to load register:", err);
      return { success: false, error: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  const setPagination = (newPagination) => {
    pagination.value = { ...pagination.value, ...newPagination };
  };

  const reset = () => {
    registers.value = [];
    isLoading.value = false;
    error.value = null;
    accountingPeriod.value = { an: null, luna: null };
    pagination.value = {
      page: 0,
      rows: 50,
      totalRecords: 0,
    };
  };

  return {
    registers,
    isLoading,
    error,
    pagination,
    totals,
    accountingPeriod,
    loadBankCashRegister,
    setPagination,
    reset,
  };
});
