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

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

  it("publishing a DRAFT item succeeds and sets lifecycle to OPEN", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftItem], [{ ...draftItem, lifecycle: "OPEN" }]);

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

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

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

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

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

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

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

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

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

    await mock.withTx((trx) => run(trx, { itemId: draftItem.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 opening an OPEN item (ITEM_NOT_DRAFT)", 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(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemNotDraftError);
    }
  });

  it("returns error when opening a CLOSED item (ITEM_NOT_DRAFT)", 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(ItemNotDraftError);
    }
  });
});
