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, ItemNotOpenError } from "../lib/errors.generated";
import { baseItem, closedItem, draftItem } from "../testing/fixtures";
import { run } from "./closePipelineItem";

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

  it("closing an OPEN item succeeds and sets lifecycle to CLOSED", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItem], [{ ...baseItem, lifecycle: "CLOSED" }]);

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

    expect(result.ok).toBe(true);
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({ lifecycle: "CLOSED" }),
    );
  });

  it("item remains in current stage after close", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItem], [{ ...baseItem, lifecycle: "CLOSED" }]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.item.stageId).toBe(baseItem.stageId);
    }
  });

  it("writes a PipelineItemChange recording OPEN → CLOSED", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItem], [{ ...baseItem, lifecycle: "CLOSED" }]);

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

    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({
        itemId: baseItem.id,
        changedByUserId: ctx.actorId,
        changeType: "LIFECYCLE",
        fieldName: "LIFECYCLE",
        prevValue: "OPEN",
        newValue: "CLOSED",
      }),
    );
  });

  it("does not create a PipelineStageTransition record", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItem], [{ ...baseItem, lifecycle: "CLOSED" }]);

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

    // The only insert is the PipelineItemChange audit row.
    expect(mock.inserts).toHaveLength(1);
    expect(mock.inserts[0].sql).not.toContain("PipelineStageTransition");
  });

  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);
    }
  });

  it("returns error when closing a DRAFT item (ITEM_NOT_OPEN)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftItem]);

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

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

  it("returns error when closing a CLOSED item (ITEM_NOT_OPEN)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([closedItem]);

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

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