import { describe, expect, it } from "vitest";

import { buildDefaultSiteSettings } from "../lib/site-settings";
import {
  applyTitleTemplateFn,
  buildAppMetadataFromConfig,
  buildLocalizedMetadataFromConfig,
} from "../lib/metadata";

describe("metadata helpers", () => {
  it("applies the configured title template", () => {
    expect(applyTitleTemplateFn("About", "{pageTitle} | {siteName}", "Studio Moh")).toBe(
      "About | Studio Moh",
    );
    expect(applyTitleTemplateFn("About", "Studio Moh", "Studio Moh")).toBe("About | Studio Moh");
  });

  it("builds root metadata with dynamic icons and social preview", () => {
    const settings = buildDefaultSiteSettings("Studio Moh");
    const metadata = buildAppMetadataFromConfig(settings, {
      siteLogoLight: null,
      siteLogoDark: null,
      favicon: {
        assetId: "fav",
        url: "/uploads/media/site-settings/favicon.svg",
        version: "v1",
      },
      defaultOgImage: {
        assetId: "og",
        url: "/uploads/media/site-settings/default-og.png",
        version: "v1",
      },
    });

    expect(metadata.title).toBe("Studio Moh");
    expect(metadata.icons).toEqual({
      icon: [{ url: "/favicon.ico?v=v1" }],
      shortcut: [{ url: "/favicon.ico?v=v1" }],
      apple: [{ url: "/apple-icon.png?v=v1" }],
    });
    expect(metadata.twitter).toMatchObject({
      card: "summary_large_image",
    });
  });

  it("falls back to localized site description and omits icons when unset", () => {
    const settings = buildDefaultSiteSettings("Studio Moh");
    settings.locales.en.siteDescription = "English fallback description";
    settings.locales.en.titleTemplate = "{pageTitle} | {siteName} | Freelancer";
    const metadata = buildLocalizedMetadataFromConfig({
      settings,
      bindings: {
        siteLogoLight: null,
        siteLogoDark: null,
        favicon: null,
        defaultOgImage: null,
      },
      locale: "en",
      pathname: "/about",
      title: "About",
    });

    expect(metadata.title).toBe("About | Studio Moh | Freelancer");
    expect(metadata.description).toBe("English fallback description");
    expect(metadata.openGraph?.siteName).toBe("Studio Moh");
    expect(metadata.twitter).toMatchObject({
      card: "summary",
    });
  });

  it("can skip the title template for the homepage", () => {
    const settings = buildDefaultSiteSettings("Studio Moh");
    settings.locales.ar.siteName = "اسم الموقع";
    settings.locales.ar.titleTemplate = "{pageTitle} | {siteName}";

    const metadata = buildLocalizedMetadataFromConfig({
      settings,
      bindings: {
        siteLogoLight: null,
        siteLogoDark: null,
        favicon: null,
        defaultOgImage: null,
      },
      locale: "ar",
      pathname: "/",
      title: "اسم الموقع",
      description: "وصف",
      applyTitleTemplate: false,
    });

    expect(metadata.title).toBe("اسم الموقع");
  });
});
