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

import { buildSiteIconResponse, buildSiteIconUrls } from "@/lib/site-icons";

describe("buildSiteIconUrls", () => {
  it("uses the default version when none is provided", () => {
    const urls = buildSiteIconUrls({ siteName: "Studio" });
    expect(urls.version).toBe("default");
    expect(urls.faviconHref).toBe("/favicon.ico?v=default");
    expect(urls.appleIconHref).toBe("/apple-icon.png?v=default");
    expect(urls.manifestHref).toBe("/manifest.webmanifest?v=default");
    expect(urls.faviconAssetUrl).toBeNull();
  });

  it("applies a provided favicon version to internal icon hrefs", () => {
    const urls = buildSiteIconUrls({ siteName: "Studio", faviconVersion: "v1" });
    expect(urls.faviconHref).toBe("/favicon.ico?v=v1");
    expect(urls.appleIconHref).toBe("/apple-icon.png?v=v1");
  });

  it("versions a relative favicon asset url", () => {
    const urls = buildSiteIconUrls({
      siteName: "Studio",
      faviconVersion: "v2",
      faviconUrl: "/uploads/media/site-settings/favicon.svg",
    });
    expect(urls.faviconAssetUrl).toBe("/uploads/media/site-settings/favicon.svg?v=v2");
  });

  it("versions an absolute favicon asset url", () => {
    const urls = buildSiteIconUrls({
      siteName: "Studio",
      faviconVersion: "v3",
      faviconUrl: "https://cdn.example.com/favicon.png",
    });
    expect(urls.faviconAssetUrl).toBe("https://cdn.example.com/favicon.png?v=v3");
  });

  it("falls back to a default site name when empty", () => {
    expect(buildSiteIconUrls({ siteName: "   " }).siteName).toBe("Moh");
  });
});

describe("buildSiteIconResponse", () => {
  it("returns a transparent png for a null icon url", async () => {
    const response = await buildSiteIconResponse(null);
    expect(response.status).toBe(200);
    expect(response.headers.get("Content-Type")).toBe("image/png");
    expect(response.headers.get("Cache-Control")).toBe("no-store, max-age=0");
    const bytes = new Uint8Array(await response.arrayBuffer());
    // PNG magic number
    expect(Array.from(bytes.slice(0, 4))).toEqual([0x89, 0x50, 0x4e, 0x47]);
  });

  it("returns the transparent fallback for unmanaged paths", async () => {
    const response = await buildSiteIconResponse("https://example.com/external.png");
    expect(response.status).toBe(200);
    expect(response.headers.get("Content-Type")).toBe("image/png");
  });
});
