import { describe, expect, it } from "vitest";
import {
  planningAgenda,
  recomputePlanningReadiness,
  type PlanningDeferral,
  type PlanningItem,
  type PlanningSession,
} from "@awp/domain";
import {
  unsafeOpaqueId,
  type PlanId,
  type PlanningSessionId,
  type ProjectId,
} from "@awp/contracts";

const item = (key: string, status: PlanningItem["status"]): PlanningItem => ({
  key,
  stage: "DEFINE",
  title: key,
  summary: `${key} summary`,
  participation: "owner-required",
  status,
});

const deferral = (blockingAt: PlanningDeferral["blockingAt"]): PlanningDeferral => ({
  itemKey: "connection",
  reason: "external setup is intentionally later",
  blockingAt,
  owner: "owner",
  consequence: "the declared later gate cannot pass",
  revisit: "before the declared gate",
  status: "open",
});

describe("I2 Planning domain", () => {
  it("uses gates rather than fake percentages for readiness", () => {
    expect(recomputePlanningReadiness([item("intent", "pending")], [])).toBe("blocked");
    expect(recomputePlanningReadiness([item("intent", "accepted")], [deferral("PRODUCTION")])).toBe(
      "ready-with-deferred-gaps",
    );
    expect(recomputePlanningReadiness([item("intent", "accepted")], [deferral("LAUNCH")])).toBe(
      "blocked",
    );
    expect(recomputePlanningReadiness([item("intent", "accepted")], [])).toBe("ready");
  });

  it("restores the durable Now / Next / Later agenda from activeItemKey", () => {
    const session = {
      id: unsafeOpaqueId<PlanningSessionId>("planning:agenda"),
      projectId: unsafeOpaqueId<ProjectId>("project:agenda"),
      planId: unsafeOpaqueId<PlanId>("plan:agenda"),
      goalIds: [],
      intent: "Ship the next slice",
      mode: "expert",
      profile: { kind: "existing-product-feature", confidence: "high", traits: [], basis: [] },
      status: "active",
      readiness: "blocked",
      activeItemKey: "scope",
      draft: "",
      items: [item("intent", "accepted"), item("scope", "active"), item("acceptance", "pending")],
      deferrals: [],
      delivery: { quality: "q", ci: "ci", delivery: "d", execution: "e", connections: [] },
      createdAt: "2026-08-24T00:00:00.000Z",
      updatedAt: "2026-08-24T00:00:00.000Z",
      revision: 2,
    } satisfies PlanningSession;

    const agenda = planningAgenda(session);
    expect(agenda.now?.key).toBe("scope");
    expect(agenda.next?.key).toBe("acceptance");
    expect(agenda.later).toHaveLength(0);
  });
});
