import mysql from "mysql2/promise";
import fallback from "../config/changelog.json";

/**
 * Changelog entries, read from cja_changelog at BUILD time.
 *
 * Same pattern as lib/projects.js: query once during the build, ship static
 * HTML, and fall back to the committed JSON if the database is unreachable so a
 * DB outage can never fail the build. The fallback is regenerated from the DB
 * whenever the changelog is reseeded, so the two stay in step.
 */

const env = import.meta.env;
let cache = null;

export async function getChangelog() {
  if (cache) return cache;

  const { DB_HOST: host, DB_NAME: database, DB_USER: user, DB_PASS: password } = env;

  if (!host || !database || !user) {
    console.warn("[changelog] No DB credentials — using config/changelog.json");
    cache = fallback;
    return cache;
  }

  let conn;
  try {
    conn = await mysql.createConnection({ host, user, password, database });
    const [rows] = await conn.execute(
      `SELECT type, summary, detail, actor,
              DATE_FORMAT(entry_at, '%Y-%m-%dT%H:%i') AS entry_at
         FROM cja_changelog
        WHERE published = 1
        ORDER BY entry_at DESC`,
    );
    cache = rows.length ? rows : fallback;
    console.log(`[changelog] loaded ${cache.length} entries`);
  } catch (error) {
    console.error(`[changelog] DB read failed (${error.message}) — using fallback`);
    cache = fallback;
  } finally {
    await conn?.end();
  }

  return cache;
}

/**
 * Group entries by calendar day, newest first, each day's entries newest first.
 * Returns [{ dateKey, dateLabel, items: [...] }].
 */
export async function getChangelogByDay() {
  const entries = await getChangelog();
  const days = new Map();

  for (const e of entries) {
    const dateKey = e.entry_at.slice(0, 10); // YYYY-MM-DD
    if (!days.has(dateKey)) days.set(dateKey, []);
    days.get(dateKey).push(e);
  }

  const fmt = new Intl.DateTimeFormat("en-GB", {
    day: "numeric",
    month: "long",
    year: "numeric",
  });

  return [...days.entries()]
    .sort((a, b) => (a[0] < b[0] ? 1 : -1))
    .map(([dateKey, items]) => ({
      dateKey,
      // parse as UTC noon to avoid any timezone date-shift
      dateLabel: fmt.format(new Date(`${dateKey}T12:00:00Z`)),
      items,
    }));
}
