import { describe, expect, it } from "vitest";
import {
  choosePlaywrightFinalResult,
  extractPlaywrightFailure,
  parsePlaywrightJsonResults,
} from "./playwright.mjs";

describe("playwright-report", () => {
  it("handles empty and invalid output", () => {
    expect(parsePlaywrightJsonResults("", "/tmp")).toEqual({
      fileResults: new Map(),
      errors: [],
    });

    const invalid = parsePlaywrightJsonResults("{", "/tmp");
    expect(invalid.errors[0]).toContain("Could not parse Playwright JSON output");
  });

  it("collects nested suite results", () => {
    const stdout = JSON.stringify({
      errors: [{ message: "reporter failure" }],
      suites: [
        {
          file: "/tmp/tests/auth.spec.js",
          specs: [
            {
              title: "auth works",
              tests: [
                {
                  outcome: "unexpected",
                  results: [
                    {
                      status: "failed",
                      duration: 15,
                      error: {
                        message: "boom\nstack",
                      },
                    },
                  ],
                },
              ],
            },
          ],
        },
      ],
    });

    const parsed = parsePlaywrightJsonResults(stdout, "/tmp");
    expect(parsed.errors).toEqual(["reporter failure"]);
    expect(parsed.fileResults.get("tests/auth.spec.js")).toEqual({
      failed: true,
      error: "boom",
      durationMs: 15,
    });
  });

  it("chooses the final result and extracts failures", () => {
    expect(
      choosePlaywrightFinalResult([
        { status: "failed" },
        { status: "passed" },
      ])
    ).toEqual({ status: "passed" });

    expect(
      extractPlaywrightFailure(
        { error: { message: "first line\nsecond line" } },
        { title: "spec title" },
        { errors: [] }
      )
    ).toBe("first line");
  });
});
