import { describe, expect, it } from "vitest";
import type { GovernanceConfig } from "@fragments-sdk/core";

import { scanWithFacts } from "../typestyle/check.js";
import { extractStyleBlockFacts } from "./style-blocks.js";

const rawColorPolicy: GovernanceConfig = {
  styles: [
    {
      kind: "style.rawColors.forbid",
      except: ["transparent", "currentColor", "inherit"],
      prefer: "token",
      severity: "error",
    },
  ],
};

describe("extractStyleBlockFacts", () => {
  it("extracts Vue style block declarations with source line offsets", () => {
    const facts = extractStyleBlockFacts(
      [
        "<template><button /></template>",
        "<style scoped>",
        ".button {",
        "  color: #2563eb;",
        "}",
        "</style>",
      ].join("\n"),
      "src/Button.vue",
    );

    expect(
      facts.map((fact) =>
        fact.kind === "style_declaration"
          ? {
              property: fact.property,
              value: fact.value,
              selector: fact.selector,
              line: fact.location.line,
            }
          : null,
      ),
    ).toEqual([
      {
        property: "color",
        value: "#2563eb",
        selector: "style-block:0:.button",
        line: 4,
      },
    ]);
  });

  it("feeds Svelte style blocks into governance rules", () => {
    const result = scanWithFacts({
      facts: { governConfig: rawColorPolicy },
      files: [
        {
          absPath: "/repo/src/Card.svelte",
          relPath: "src/Card.svelte",
          content: [
            "<script>export let title;</script>",
            "<style>",
            ".card { border-color: #0f172a; }",
            "</style>",
            "<article>{title}</article>",
          ].join("\n"),
        },
      ],
    });

    expect(result.filesScanned).toEqual(["src/Card.svelte"]);
    expect(result.findings).toEqual([
      expect.objectContaining({
        ruleId: "styles/no-raw-color",
        location: expect.objectContaining({ file: "src/Card.svelte", line: 3 }),
        attributes: expect.objectContaining({
          property: "border-color",
          rawValue: "#0f172a",
        }),
      }),
    ]);
  });
});
