// Run with: node --experimental-strip-types --test test/*.test.ts
// (Node's built-in runner — no Workers runtime / dev-server dependency.)
import { test } from "node:test";
import assert from "node:assert/strict";
import { latestDmgUrl } from "../src/appcast.ts";

const BASE = "https://updates.nucleic.blakeslee.xyz";

// Two releases, deliberately listed oldest-first so we prove ranking is by sparkle:version
// (the build number), not document order.
const appcast = `<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle" version="2.0">
  <channel>
    <title>Nucleic Beta</title>
    <item>
      <title>0.1.0</title>
      <enclosure url="${BASE}/beta/Nucleic-Beta-0.1.0.828.dmg" sparkle:version="828"
        length="35714227" type="application/octet-stream"
        sparkle:edSignature="AAAA==" />
    </item>
    <item>
      <title>0.2.0</title>
      <enclosure url="${BASE}/beta/Nucleic-Beta-0.2.0.829.dmg" sparkle:version="829"
        length="35714300" type="application/octet-stream"
        sparkle:edSignature="BBBB==" />
    </item>
  </channel>
</rss>`;

test("picks the highest-build DMG regardless of item order", () => {
  assert.equal(latestDmgUrl(appcast), `${BASE}/beta/Nucleic-Beta-0.2.0.829.dmg`);
});

test("returns the lone enclosure when there is just one release", () => {
  const one = `<rss><channel><item><enclosure url="${BASE}/rc/Nucleic-RC-1.0.0.500.dmg" sparkle:version="500" /></item></channel></rss>`;
  assert.equal(latestDmgUrl(one), `${BASE}/rc/Nucleic-RC-1.0.0.500.dmg`);
});

test("ignores non-DMG enclosures (e.g. delta/patch entries)", () => {
  const withDelta = `<rss><channel><item>
    <enclosure url="${BASE}/beta/Nucleic-Beta-0.2.0.829.delta" sparkle:version="829" sparkle:deltaFrom="828" />
    <enclosure url="${BASE}/beta/Nucleic-Beta-0.2.0.829.dmg" sparkle:version="829" />
  </item></channel></rss>`;
  assert.equal(latestDmgUrl(withDelta), `${BASE}/beta/Nucleic-Beta-0.2.0.829.dmg`);
});

test("returns null for an appcast with no releases", () => {
  assert.equal(latestDmgUrl(`<rss><channel><title>empty</title></channel></rss>`), null);
});

test("returns null for empty / junk input", () => {
  assert.equal(latestDmgUrl(""), null);
  assert.equal(latestDmgUrl("not xml at all"), null);
});
