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

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

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

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

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

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

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

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

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

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

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

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

    await mock.withTx((trx) => run(trx, { itemId: closedItem.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 reopening an OPEN item (ITEM_NOT_CLOSED)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...closedItem, lifecycle: "OPEN" }]);

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

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

  it("returns error when reopening a DRAFT item (ITEM_NOT_CLOSED)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...closedItem, lifecycle: "DRAFT" }]);

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

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