import { apiDownloadFile } from "@/lib/api";

export type ExportFormat = "xlsx" | "pdf" | "csv";
export type ExportScope = "filtered" | "all";

export function hasUserFilters(
  filters: Record<string, string | number | boolean | null | undefined>,
  contextKeys: string[] = [],
): boolean {
  const context = new Set(contextKeys);
  return Object.entries(filters).some(([key, value]) => {
    if (context.has(key)) return false;
    if (value === null || value === undefined) return false;
    if (typeof value === "string") return value.trim() !== "";
    if (typeof value === "boolean") return value;
    return true;
  });
}

export function buildExportQuery(
  filters: Record<string, string | number | boolean | null | undefined>,
  format: ExportFormat,
  scope: ExportScope,
): string {
  const params = new URLSearchParams();
  params.set("format", format);
  params.set("export_scope", scope);
  Object.entries(filters).forEach(([key, value]) => {
    if (value === null || value === undefined) return;
    if (typeof value === "string" && value.trim() === "") return;
    params.set(key, String(value));
  });
  return params.toString();
}

export async function downloadListExport(
  exportPath: string,
  filters: Record<string, string | number | boolean | null | undefined>,
  format: ExportFormat,
  scope: ExportScope,
  fallbackName: string,
): Promise<void> {
  const query = buildExportQuery(filters, format, scope);
  const separator = exportPath.includes("?") ? "&" : "?";
  await apiDownloadFile(`${exportPath}${separator}${query}`, `${fallbackName}.${format}`);
}
