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

import {
  buildDefaultSiteSettings,
  parseSiteSettingsValue,
} from "../lib/site-settings";

describe("site settings helpers", () => {
  it("builds defaults from the fallback site name", () => {
    const settings = buildDefaultSiteSettings("Studio Moh");

    expect(settings.locales.ar.siteName).toBe("Studio Moh");
    expect(settings.locales.ar.titleTemplate).toBe("{pageTitle} | {siteName}");
    expect(settings.locales.en.siteDescription).toBe("Multilingual Next.js base project");
    expect(settings.locales.de.subhead).toBe("");
  });

  it("merges stored values with safe defaults", () => {
    const settings = parseSiteSettingsValue(
      JSON.stringify({
        locales: {
          en: {
            siteName: "Brand EN",
            titleTemplate: "{pageTitle} - {siteName}",
            siteDescription: "English description",
          },
          de: {
            siteName: "Brand DE",
            titleTemplate: "{pageTitle} | {siteName} | Freelancer",
            subhead: "German subhead",
          },
        },
      }),
      "Fallback Name",
    );

    expect(settings.locales.en.siteName).toBe("Brand EN");
    expect(settings.locales.en.titleTemplate).toBe("{pageTitle} - {siteName}");
    expect(settings.locales.en.siteDescription).toBe("English description");
    expect(settings.locales.en.subhead).toBe("");
    expect(settings.locales.ar.siteName).toBe("Fallback Name");
    expect(settings.locales.ar.titleTemplate).toBe("{pageTitle} | {siteName}");
    expect(settings.locales.de.siteDescription).toBe("Multilingual Next.js base project");
    expect(settings.locales.de.titleTemplate).toBe("{pageTitle} | {siteName} | Freelancer");
    expect(settings.locales.de.subhead).toBe("German subhead");
  });

  it("falls back when stored json is invalid", () => {
    const settings = parseSiteSettingsValue("{invalid-json", "Fallback Name");

    expect(settings).toEqual(buildDefaultSiteSettings("Fallback Name"));
  });

  it("ignores legacy top-level title template values", () => {
    const settings = parseSiteSettingsValue(
      JSON.stringify({
        titleTemplate: "{pageTitle} | moh-sass | Legacy",
        locales: {
          ar: {
            siteName: "اسم الموقع",
          },
        },
      }),
      "Fallback Name",
    );

    expect(settings.locales.ar.titleTemplate).toBe("{pageTitle} | {siteName}");
  });
});
