import api from "src/api";

export const getRelatorioCounters = async () => {
  const { data } = await api.get("/relatorio/counters");
  return data.payload;
};

export const getNovoAssociadosPaginated = async ({ page = 1, perPage = 10, filter } = {}) => {
  const params = { page, per_page: perPage };
  if (filter) params.search = filter;
  const { data } = await api.get("/relatorio/novos-associados", { params });
  return { data: { result: data.payload } };
};

export const getContatosAssociadosPaginated = async ({ page = 1, perPage = 10, filter } = {}) => {
  const params = { page, per_page: perPage };
  if (filter) params.search = filter;
  const { data } = await api.get("/relatorio/contatos-associados", { params });
  return { data: { result: data.payload } };
};

export const getExclusoesMesPaginated = async ({ page = 1, perPage = 10, filter } = {}) => {
  const params = { page, per_page: perPage };
  if (filter) params.search = filter;
  const { data } = await api.get("/relatorio/exclusoes-mes", { params });
  return { data: { result: data.payload } };
};

export const exportRelatorio = async (tipo, search) => {
  const nomes = {
    "novos-associados": "novos_associados",
    "contatos-associados": "contatos_associados",
    "exclusoes-mes": "exclusoes_mes",
  };

  const hoje = new Date();
  const dd = String(hoje.getDate()).padStart(2, "0");
  const mm = String(hoje.getMonth() + 1).padStart(2, "0");
  const yyyy = hoje.getFullYear();
  const filename = `${nomes[tipo]}_${dd}-${mm}-${yyyy}.xlsx`;

  const params = {};
  if (search) params.search = search;

  const response = await api.get(`/relatorio/${tipo}/export`, {
    responseType: "blob",
    params,
  });

  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", filename);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
};
