/**
 * SET 19d — client-side download helpers for Admin metrics export.
 */

export function downloadTextFile(filename: string, contents: string, mime = 'text/plain'): void {
  const blob = new Blob([contents], { type: `${mime};charset=utf-8` });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.rel = 'noopener';
  document.body.appendChild(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(url);
}

export function metricsExportDate(d = new Date()): string {
  return d.toISOString().slice(0, 10);
}

export function exportInstallMetricsFiles(opts: {
  /** SET 24d — plumbing only: kept in file content (see statsAggregate JSON/CSV), never in the filename. */
  installHash?: string;
  csv: string;
  json: object;
}): void {
  const date = metricsExportDate();
  downloadTextFile(`metrics-${date}.csv`, opts.csv, 'text/csv');
  downloadTextFile(
    `metrics-${date}.json`,
    JSON.stringify(opts.json, null, 2) + '\n',
    'application/json',
  );
}

export function exportSiteStatsFile(stats: object): void {
  const date = metricsExportDate();
  downloadTextFile(
    `site-stats-${date}.json`,
    JSON.stringify(stats, null, 2) + '\n',
    'application/json',
  );
}
