import { describe, expect, test } from "bun:test";
import { lifecycleTransitions, type KubernetesLifecycleObject } from "./kubernetes-lifecycle";

const pod = (overrides: Partial<KubernetesLifecycleObject> = {}): KubernetesLifecycleObject => ({
  uid: "pod-1", resourceVersion: "10", kind: "Pod", namespace: "builds", name: "build-pod",
  nodeName: "builder-1", buildKey: "repo:sha", startedAt: "2026-08-08T10:00:00.000Z", phase: "Running", ...overrides,
});

describe("Kubernetes lifecycle transitions", () => {
  test("emits scheduled and started once with exact correlation fields", () => {
    const events = lifecycleTransitions(new Map(), [pod()], "2026-08-08T10:00:01.000Z");
    expect(events.map((event) => event.detail?.transition)).toEqual(["scheduled", "started"]);
    expect(events[0]).toMatchObject({ source: "kubernetes", category: "buildbox", host: "builder-1", detail: { workloadUid: "pod-1", buildKey: "repo:sha" } });
    expect(lifecycleTransitions(new Map([["pod-1", pod()]]), [pod()], "2026-08-08T10:01:00.000Z")).toEqual([]);
  });

  test("emits terminal and deletion transitions without treating an absent value as a sample", () => {
    const before = pod();
    const failed = pod({ resourceVersion: "11", phase: "Failed", finishedAt: "2026-08-08T10:02:00.000Z", reason: "Error" });
    const terminal = lifecycleTransitions(new Map([[before.uid, before]]), [failed], "2026-08-08T10:02:01.000Z");
    expect(terminal).toHaveLength(1);
    expect(terminal[0]).toMatchObject({ severity: "error", ts: failed.finishedAt, detail: { transition: "failed", reason: "Error" } });
    const deleted = lifecycleTransitions(new Map([[failed.uid, failed]]), [], "2026-08-08T10:03:00.000Z");
    expect(deleted[0]).toMatchObject({ detail: { transition: "deleted", resourceVersion: "11" } });
  });
});
