import { api } from "./api";

/**
 * @param {string} resourceKey - e.g. 'users'
 * @param {import('axios').AxiosRequestConfig} [config]
 */
export async function getDataTableColumns(resourceKey, config = {}) {
  const encoded = encodeURIComponent(resourceKey);
  const { data } = await api.get(
    `/api/datatables/${encoded}/columns`,
    config,
  );
  return data;
}

/**
 * @param {string} resourceKey
 * @param {object} payload
 * @param {import('axios').AxiosRequestConfig} [config]
 */
export async function fetchDataTable(resourceKey, payload, config = {}) {
  const encoded = encodeURIComponent(resourceKey);
  const { data } = await api.post(`/api/datatables/${encoded}`, payload, config);
  return data;
}

export async function exportDataTable(resourceKey, payload) {
  const encoded = encodeURIComponent(resourceKey);
  const { data } = await api.post(`/api/datatables/${encoded}/export`, payload);
  return data;
}

export async function getDataTableExportStatus(exportId) {
  const encoded = encodeURIComponent(exportId);
  const { data } = await api.get(`/api/datatables/exports/${encoded}`);
  return data;
}

export async function listDataTableExports() {
  const { data } = await api.get("/api/datatables/exports");
  return data;
}

export async function downloadDataTableExport(exportId, suggestedName) {
  const encoded = encodeURIComponent(exportId);
  const response = await api.get(
    `/api/datatables/exports/${encoded}/download`,
    {
      responseType: "blob",
    },
  );

  const disposition =
    response.headers["content-disposition"] ||
    response.headers["Content-Disposition"];
  let filename = "export.csv";
  if (disposition && typeof disposition === "string") {
    const match = disposition.match(/filename="?([^"]+)"?/i);
    if (match && match[1]) {
      filename = match[1];
    }
  } else if (suggestedName) {
    filename = `export-${suggestedName}.csv`;
  }

  const blob = response.data;
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  link.remove();
  window.URL.revokeObjectURL(url);
}

export async function clearReadyDataTableExports() {
  const { data } = await api.post("/api/datatables/exports/clear-ready");
  return data;
}
