import { expect, test } from "bun:test";

import { decideAndMaybeTriggerForTest } from "./cicd-branch-follower";
import type { AdapterSummary, BranchFollowerRegistry, FollowerSpec, ParsedOptions } from "./cicd-types";

test("PaC 随机后缀 current PipelineRun 在无 stored trigger 时继续 closeout", async () => {
  const observedSha = "09a1273bbea1d591aaa00b0e27af08f3234c8123";
  const pipelineRun = "hwlab-nc01-v03-ci-poll-8nthq";
  const follower = {
    id: "hwlab-nc01-v03",
    enabled: true,
    deliveryAuthority: "retired-readonly",
    adapter: "hwlab-node-runtime",
    description: "fixture",
    source: {
      repository: "pikasTech/hwlab",
      branch: "v0.3",
      branchRef: "refs/heads/v0.3",
      authorityRef: "refs/heads/v0.3",
      snapshotPrefix: "refs/unidesk/snapshots/gitea-actions/hwlab-v0.3",
      snapshotRef: "refs/unidesk/snapshots/gitea-actions/hwlab-v0.3/current",
    },
    target: { node: "NC01", lane: "v03", namespace: "hwlab", sentinel: null, configRefs: {} },
    budgets: {
      endToEndSeconds: 300,
      statusSeconds: 30,
      triggerSeconds: 30,
      sourceSyncSeconds: 30,
      controlPlaneRefreshSeconds: 30,
      capabilityJobTtlSeconds: 300,
      capabilityJobBackoffLimit: 0,
    },
    commands: {
      plan: { argv: [], timeoutSeconds: 30 },
      status: { argv: [], timeoutSeconds: 30 },
      trigger: { argv: [], timeoutSeconds: 30 },
      events: { argv: [], timeoutSeconds: 30 },
      logs: { argv: [], timeoutSeconds: 30 },
    },
    nativeStatus: {
      source: { gitMirrorReadUrl: "ssh://fixture", gitMirrorNamespace: "fixture", gitMirrorDeployment: "fixture", repoPath: "fixture" },
      tekton: { namespace: "hwlab", pipelineRunPrefix: "hwlab-nc01-v03-ci-poll" },
      argo: null,
      runtime: null,
    },
    drillDown: null,
    closeoutChecks: [],
  } as FollowerSpec;
  const registry = {
    controller: { stateConfigMapName: "fixture-state", leaseName: "fixture-lease" },
  } as BranchFollowerRegistry;
  const live = {
    ok: true,
    command: "native:k8s-git-mirror+tekton+argocd+runtime",
    exitCode: 0,
    timedOut: false,
    observedSha,
    targetSha: null,
    lastTriggeredSha: null,
    lastSucceededSha: null,
    pipelineRun,
    pipelineRunPresent: true,
    inFlightJob: pipelineRun,
    aligned: false,
    phase: "PendingTrigger",
    message: "current source PipelineRun is still running",
    payload: null,
    stderrTail: "",
    stdoutTail: "",
  } as AdapterSummary;
  const options = {
    confirm: false,
    dryRun: false,
    wait: false,
    inCluster: false,
  } as ParsedOptions;

  const state = await decideAndMaybeTriggerForTest(registry, follower, {}, live, options);

  expect(state).toMatchObject({
    phase: "ClosingOut",
    lastTriggeredSha: observedSha,
    pipelineRun,
    inFlightJob: pipelineRun,
    decision: "same sha was already triggered; use status/events/logs for closeout",
  });
});
