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,
  LabelAlreadyAttachedError,
  LabelNotFoundError,
  LabelNotOnItemPipelineError,
} from "../lib/errors.generated";
import {
  baseItem,
  basePipelineItemLabel,
  baseLabel,
  otherPipelineLabel,
} from "../testing/fixtures";
import { run } from "./attachLabelToPipelineItem";

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

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

  it("attaches a label that belongs to the same pipeline as the item", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItem], [baseLabel], [], [basePipelineItemLabel], []);

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

    expect(result.ok).toBe(true);
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ itemId: input.itemId, labelId: input.labelId }),
    );
  });

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

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

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

  it("returns error when item does not exist", 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(ItemNotFoundError);
    }
  });

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

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

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

  it("returns error when label belongs to a different pipeline", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItem], [otherPipelineLabel]);

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

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

  it("returns error when label is already attached", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItem], [baseLabel], [basePipelineItemLabel]);

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

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