import { describe, expect, it } from "vitest";
import {
  collectFailureDetailsFromRuntimeArtifacts,
  mergeFailureDetails,
} from "./failure-details.mjs";

describe("runner failure details", () => {
  it("merges duplicate failure details by kind and key", () => {
    expect(
      mergeFailureDetails([
        { kind: "k6-check", key: "group > check", title: "check" },
        { kind: "k6-check", key: "group > check", title: "check" },
        { kind: "playwright-spec", key: "spec title", title: "spec title" },
      ])
    ).toEqual([
      {
        kind: "k6-check",
        key: "group > check",
        title: "check",
        count: 2,
      },
      {
        kind: "playwright-spec",
        key: "spec title",
        title: "spec title",
        count: 1,
      },
    ]);
  });

  it("extracts and normalizes runtime failure-detail artifacts", () => {
    expect(
      collectFailureDetailsFromRuntimeArtifacts([
        {
          kind: "testkit.failure-details",
          data: {
            phase: "exec",
            failures: [
              {
                kind: "k6-check",
                key: "status is 200",
                title: "status is 200",
              },
              {
                kind: "k6-check",
                key: "status is 200",
                title: "status is 200",
              },
            ],
          },
        },
      ])
    ).toEqual([
      {
        kind: "k6-check",
        key: "status is 200",
        title: "status is 200",
        count: 2,
        phase: "exec",
      },
    ]);
  });

  it("preserves rich assertion metadata", () => {
    expect(
      mergeFailureDetails([
        {
          kind: "http-assertion",
          key: "GET /health > status is 200",
          title: "status is 200",
          expected: 200,
          actual: 404,
          request: {
            method: "GET",
            path: "/health",
            requestId: "req-1",
          },
          response: {
            status: 404,
            bodyPreview: '{"error":"nope"}',
          },
          location: {
            path: "/tmp/example.ts",
            line: 12,
            column: 4,
          },
        },
      ])
    ).toEqual([
      {
        kind: "http-assertion",
        key: "GET /health > status is 200",
        title: "status is 200",
        count: 1,
        expected: 200,
        actual: 404,
        request: {
          method: "GET",
          path: "/health",
          requestId: "req-1",
        },
        response: {
          status: 404,
          bodyPreview: '{"error":"nope"}',
        },
        location: {
          path: "/tmp/example.ts",
          line: 12,
          column: 4,
        },
      },
    ]);
  });
});
