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 { LabelNotAttachedError } from "../lib/errors.generated";
import { baseItem, basePipelineItemLabel, baseLabel } from "../testing/fixtures";
import { run } from "./detachLabelFromPipelineItem";

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

  const input = { itemId: baseItem.id, labelId: baseLabel.id };

  it("detaches an existing label from the item", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipelineItemLabel], [], []);

    const result = await mock.withTx((trx) => run(trx, input, ctx));

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

  it("writes a PipelineItemChange for label detach", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipelineItemLabel], [], []);

    await mock.withTx((trx) => run(trx, input, ctx));

    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({
        itemId: input.itemId,
        changedByUserId: ctx.actorId,
        changeType: "LABEL",
        fieldName: "LABEL",
        prevValue: input.labelId,
        newValue: null,
      }),
    );
  });

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

    const result = await mock.withTx((trx) => run(trx, input, ctx));

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