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 { LabelNotFoundError } from "../lib/errors.generated";
import { baseLabel } from "../testing/fixtures";
import { run } from "./deletePipelineLabel";

describe("deletePipelineLabel", () => {
  const ctx: CommandContext = {
    actorId: "user-1",
    permissions: ["pipeline-management:label:deletePipelineLabel"],
  };

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

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

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

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

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

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