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 {
  PipelineLockedError,
  StageHasItemsError,
  StageNotFoundError,
} from "../lib/errors.generated";
import { baseItem, basePipeline, baseStage, lockedPipeline } from "../testing/fixtures";
import { run } from "./deletePipelineStage";

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

  it("deletes an empty stage", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseStage], [basePipeline], []);

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

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

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

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

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

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

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

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

  it("returns error when stage has items", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseStage], [basePipeline], [baseItem]);

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

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