/**
 * The pure parts of the detail routes' metadata.
 *
 * `metaDescription` is the interesting one: descriptions are stored as HTML
 * (the CMS and the rich-text editor both write markup), and a `<p>` tag in a
 * `<meta name="description">` is worse than no description at all.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";

import {
  metaDescription,
  metaTitle,
} from "@/features/shared/services/detailMetadata";

describe("metaTitle", () => {
  test("prefers the English title", () => {
    assert.equal(
      metaTitle({ title_en: "Beach cleanup", title_ar: "تنظيف الشاطئ" }, "x"),
      "Beach cleanup"
    );
  });

  test("falls back to Arabic when English is missing or empty", () => {
    assert.equal(metaTitle({ title_ar: "تنظيف الشاطئ" }, "x"), "تنظيف الشاطئ");
    assert.equal(
      metaTitle({ title_en: "", title_ar: "تنظيف الشاطئ" }, "x"),
      "تنظيف الشاطئ"
    );
  });

  test("falls back to the generic title for a failed read", () => {
    assert.equal(metaTitle(null, "Event"), "Event");
    assert.equal(metaTitle({}, "Event"), "Event");
    assert.equal(metaTitle({ title_en: null, title_ar: null }, "Event"), "Event");
  });
});

describe("metaDescription", () => {
  test("strips HTML, because descriptions are stored as markup", () => {
    assert.equal(
      metaDescription(
        { description_en: "<p>Join us at <strong>Messilah</strong> beach.</p>" },
        "fallback"
      ),
      "Join us at Messilah beach."
    );
  });

  test("collapses the whitespace left behind by the stripped tags", () => {
    assert.equal(
      metaDescription({ description_en: "<p>One</p>\n\n<p>Two</p>" }, "fallback"),
      "One Two"
    );
  });

  test("clips to 160 characters with an ellipsis", () => {
    const long = "a".repeat(500);
    const out = metaDescription({ description_en: long }, "fallback");
    assert.equal(out.length, 158);
    assert.ok(out.endsWith("…"));
  });

  test("a description that is only markup yields the fallback, not an empty tag", () => {
    assert.equal(metaDescription({ description_en: "<p></p>" }, "fallback"), "fallback");
    assert.equal(metaDescription({ description_en: "   " }, "fallback"), "fallback");
  });

  test("falls back for a failed read", () => {
    assert.equal(metaDescription(null, "fallback"), "fallback");
    assert.equal(metaDescription({}, "fallback"), "fallback");
  });

  test("uses the Arabic description when English is absent", () => {
    assert.equal(
      metaDescription({ description_ar: "<p>انضم إلينا</p>" }, "fallback"),
      "انضم إلينا"
    );
  });
});
