function parseCreatedAt(doc) {
  const raw = doc?.issued_at ?? doc?.created_at;
  if (!raw) return null;
  const date = new Date(raw);
  if (Number.isNaN(date.getTime())) return null;
  return date;
}

function monthKey(date) {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
}

export function chartScaleMax(maxValue) {
  const n = Number(maxValue) || 0;
  if (n <= 0) return 5;
  if (n <= 5) return 5;
  if (n <= 10) return 10;
  const mag = 10 ** Math.floor(Math.log10(n));
  const norm = n / mag;
  const ceilNorm = norm <= 1 ? 1 : norm <= 2 ? 2 : norm <= 5 ? 5 : 10;
  return ceilNorm * mag;
}

/** Monthly SWI document creation counts for the last N months. */
export function buildDocumentCreationTrend(documents = [], monthCount = 12) {
  const safeCount = Math.max(Number(monthCount) || 12, 1);
  const now = new Date();
  const buckets = new Map();

  for (let offset = safeCount - 1; offset >= 0; offset -= 1) {
    const date = new Date(now.getFullYear(), now.getMonth() - offset, 1);
    const key = monthKey(date);
    buckets.set(key, {
      period: key,
      label: date.toLocaleDateString(undefined, {
        month: "short",
        year: "2-digit",
      }),
      count: 0,
    });
  }

  for (const doc of documents) {
    const created = parseCreatedAt(doc);
    if (!created) continue;
    const key = monthKey(created);
    if (buckets.has(key)) {
      buckets.get(key).count += 1;
    }
  }

  return Array.from(buckets.values());
}
