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 { ItemNotFoundError } from "../lib/errors.generated";
import { baseItem } from "../testing/fixtures";
import { run } from "./deletePipelineItem";

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

  it("deletes the item and cascades its dependent rows", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItem], [], [], [], [], []);

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

    expect(result.ok).toBe(true);
    expect(mock.deletes.map((d) => d.sql)).toEqual([
      expect.stringContaining('"PipelineItemLabel"'),
      expect.stringContaining('"PipelineItemComment"'),
      expect.stringContaining('"PipelineItemChange"'),
      expect.stringContaining('"PipelineStageTransition"'),
      expect.stringContaining('"PipelineItem"'),
    ]);
  });

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

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

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