import { describe, it, expect } from "vitest";
import { buildEmailContent } from "./build-email-content";

describe("buildEmailContent", () => {
  it("does not inject a pixel when no tracking token is given", () => {
    const content = buildEmailContent("<html><body><p>Hello</p></body></html>", "contact-1");

    expect(content.html).not.toContain("/api/track/open/");
  });

  it("injects the open-tracking pixel when a tracking token is given", () => {
    const content = buildEmailContent(
      "<html><body><p>Hello</p></body></html>",
      "contact-1",
      "log-1"
    );

    expect(content.html).toContain("/api/track/open/log-1.gif");
  });

  it("strips a pre-existing tracking pixel before injecting the new one", () => {
    const html =
      '<html><body><p>Hello</p><img src="https://old.example.com/api/track/open/stale.gif" /></body></html>';

    const content = buildEmailContent(html, "contact-1", "log-1");

    expect(content.html).not.toContain("stale.gif");
    expect(content.html.match(/\/api\/track\/open\//g)).toHaveLength(1);
  });

  it("adds an unsubscribe link when the HTML does not already have one", () => {
    const content = buildEmailContent("<html><body><p>Hello</p></body></html>", "contact-1");

    expect(content.html).toContain("/unsubscribe/contact-1");
    expect(content.headers["List-Unsubscribe"]).toContain("/unsubscribe/contact-1");
  });
});
