import { describe, expect, it } from "vitest";
import {
  addTrackerError,
  buildRunArtifact,
  buildServiceTrackers,
  finalizeServiceResult,
  formatDuration,
  formatError,
  formatServiceSummary,
  recordGraphError,
  recordTaskOutcome,
  summarizeDbBackend,
} from "./results.mjs";

describe("runner-results", () => {
  it("tracks task outcomes and graph errors", () => {
    const trackers = buildServiceTrackers(
      [
        {
          skipped: false,
          config: {
            name: "api",
            testkit: {
              database: {
                selectedBackend: "local",
              },
            },
          },
          suites: [
            {
              name: "health",
              type: "integration",
              framework: "k6",
              files: ["tests/health.js"],
              orderIndex: 0,
            },
          ],
        },
      ],
      1000
    );

    recordTaskOutcome(
      trackers,
      {
        serviceName: "api",
        suiteKey: "integration:health",
        file: "tests/health.js",
      },
      {
        failed: true,
        durationMs: 250,
        error: "boom",
      },
      1250
    );

    const tracker = trackers.get("api");
    addTrackerError(tracker, "worker failed");
    addTrackerError(tracker, "worker failed");
    recordGraphError(trackers, { assignedTargets: ["api"] }, "graph failed", 1300);

    const result = finalizeServiceResult(tracker, 1000, 1500);
    expect(result.failed).toBe(true);
    expect(result.failedSuiteCount).toBe(1);
    expect(result.errors).toEqual(["worker failed", "graph failed"]);
    expect(result.suites[0].files).toEqual([
      {
        path: "tests/health.js",
        failed: true,
        durationMs: 250,
        error: "boom",
      },
    ]);
  });

  it("builds run artifacts and formatting helpers", () => {
    const results = [
      {
        name: "api",
        failed: false,
        skipped: false,
        suiteCount: 1,
        completedSuiteCount: 1,
        failedSuiteCount: 0,
        durationMs: 1200,
        dbBackend: "local",
        suites: [],
        errors: [],
      },
      {
        name: "frontend",
        failed: false,
        skipped: true,
        suiteCount: 0,
        completedSuiteCount: 0,
        failedSuiteCount: 0,
        durationMs: 0,
        dbBackend: null,
        suites: [],
        errors: [],
      },
    ];

    const artifact = buildRunArtifact({
      productDir: "/tmp/my-product",
      results,
      startedAt: 1000,
      finishedAt: 4000,
      requestedJobs: 2,
      workerCount: 1,
      suiteType: "all",
      suiteNames: [],
      framework: "all",
      shard: null,
      serviceFilter: null,
      metadata: {
        git: {
          branch: "main",
          commitSha: "abc",
          repoRoot: "/tmp",
        },
        host: {
          hostname: "local",
          username: "dev",
        },
        testkitVersion: "0.1.17",
      },
    });

    expect(artifact.product.name).toBe("my-product");
    expect(artifact.summary.services.total).toBe(1);
    expect(summarizeDbBackend(results)).toBe("local");
    expect(formatDuration(65_000)).toBe("1m 05s");
    expect(
      formatServiceSummary({
        completedSuiteCount: 2,
        failedSuiteCount: 1,
        suiteCount: 3,
      })
    ).toBe("1/3 suites passed, 1 not run");
    expect(formatError(new Error("boom"))).toBe("boom");
  });
});
