import { useState } from "react";
import instance from "../../../utils/axios.instance";

export default function useReports() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [data, setData] = useState(null);

  const fetchReportsByCompany = async ({ table_prefix, company_nit }) => {
    setLoading(true);
    setError(null);

    try {
      const res = await instance.post("/api/home/company", {
        table_prefix,
        company_nit,
      });

      setData(res.data);
      return res.data;
    } catch (err) {
      setError(err.response?.data || { error: "Error de conexión" });
      throw err;
    } finally {
      setLoading(false);
    }
  };

  //Traer reports agrupados por mes y año de todas las empresas
  const fetchReportsGrouped = async ({ table_prefix }) => {
    setLoading(true);
    setError(null);

    try {

      const res = await instance.post("/api/home/grouped", {
        table_prefix,
      });


      setData(res.data);
      return res.data;
    } catch (err) {
      setError(err.response?.data || { error: "Error de conexión" });
      throw err;
    } finally {
      setLoading(false);
    }
  };

  return { 
    fetchReportsByCompany, 
    fetchReportsGrouped, 
    data, 
    loading, 
    error 
  };
}
