import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { PipelineNotFoundError, InvalidStatusTransitionError } from "../lib/errors.generated";
import { archivedPipeline, basePipeline } from "../testing/fixtures";
import { run } from "./deactivatePipeline";

describe("deactivatePipeline", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["pipeline-management:pipeline:deactivatePipeline"],
  };

  it("archives an active pipeline", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipeline], [{ ...basePipeline, status: "ARCHIVED" }]);

    const result = await mock.withTx((trx) => run(trx, { pipelineId: basePipeline.id }, ctx));

    expect(result.ok).toBe(true);
    expect(mock.updates[0].updateValues()).toEqual(expect.objectContaining({ status: "ARCHIVED" }));
  });

  it("is idempotent when pipeline is already archived", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([archivedPipeline]);

    const result = await mock.withTx((trx) => run(trx, { pipelineId: archivedPipeline.id }, ctx));

    expect(result.ok).toBe(true);
    expect(mock.updates.length).toBe(0);
  });

  it("returns error when pipeline not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { pipelineId: "missing-pipeline" }, ctx));

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(PipelineNotFoundError);
    }
  });

  it("returns INVALID_STATUS_TRANSITION when the stored status is outside the lifecycle", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    // A status outside the lifecycle can only come from corrupt data; the
    // lifecycle guard still refuses to archive it.
    // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- forge a corrupt status to hit the lifecycle guard
    mock.enqueueResults([{ ...basePipeline, status: "UNKNOWN" as typeof basePipeline.status }]);

    const result = await mock.withTx((trx) => run(trx, { pipelineId: basePipeline.id }, ctx));

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusTransitionError);
    }
  });
});
