import { describe, expect, test } from "bun:test";
import { parseStorefront } from "../src/main.ts";

describe("parseStorefront", () => {
  test("parses 1 meta robots + 1 canonical", () => {
    const html = `<!doctype html>
<html>
<head>
<meta name="robots" content="index,follow">
<link rel="canonical" href="https://example.com/foo">
</head>
<body></body>
</html>`;
    const r = parseStorefront(html);
    expect(r.robots).toHaveLength(1);
    expect(r.robots[0]?.content).toBe("index,follow");
    expect(r.robots[0]?.line).toBeGreaterThan(0);
    expect(r.canonicals).toEqual(["https://example.com/foo"]);
  });

  test("detects duplicate meta robots tags", () => {
    const html = `<head>
<meta name="robots" content="noindex">
<meta name="robots" content="index,follow">
</head>`;
    const r = parseStorefront(html);
    expect(r.robots).toHaveLength(2);
    expect(r.robots.map((x) => x.content)).toEqual(["noindex", "index,follow"]);
  });

  test("returns empty canonicals when none present", () => {
    const html = `<head><meta name="robots" content="index"></head>`;
    const r = parseStorefront(html);
    expect(r.canonicals).toEqual([]);
  });

  test("detects CleanSerp markers (app block comment + head injection)", () => {
    const html = `<head>
<!-- BEGIN app block: cleanserp-seo -->
<script>document.head.prepend(meta);</script>
<!-- END app block -->
</head>`;
    const r = parseStorefront(html);
    expect(r.appBlocks).toEqual(["cleanserp-seo"]);
    expect(r.cleanSerpJS).toBe(true);
    expect(r.oldGadget).toBe(false);
  });

  test("headPreview is truncated to the first 30 lines of <head>", () => {
    const lines: string[] = [];
    for (let i = 0; i < 50; i++) lines.push(`  <meta name="x${i}" content="v${i}">`);
    // Inline `<head>` (no trailing newline before content) so the 30-line slice
    // starts on the first <meta>.
    const html = `<head>${lines.join("\n")}\n</head>`;
    const r = parseStorefront(html);
    expect(r.headPreview).toHaveLength(30);
    expect(r.headPreview[0]).toContain("x0");
    expect(r.headPreview[29]).toContain("x29");
  });
});
