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 {
  PipelineLockedError,
  PipelineArchivedError,
  PipelineNotFoundError,
  DuplicateStageNameError,
  InvalidCategoryError,
  InvalidNameError,
} from "../lib/errors.generated";
import {
  inProgressStage,
  archivedPipeline,
  basePipeline,
  baseStage,
  doneStage,
  lockedPipeline,
} from "../testing/fixtures";
import { run } from "./createPipelineStage";

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

  const input = {
    pipelineId: basePipeline.id,
    name: inProgressStage.name,
    position: inProgressStage.position,
    category: inProgressStage.category,
    color: inProgressStage.color ?? undefined,
  };

  it("creates stage on active pipeline", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipeline], [], [baseStage], [inProgressStage]);

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

    expect(result.ok).toBe(true);
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ pipelineId: basePipeline.id, name: inProgressStage.name }),
    );
  });

  it("clamps an out-of-range position to the end without touching siblings", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [basePipeline],
      [],
      [baseStage, inProgressStage],
      [{ ...doneStage, position: 3 }],
    );

    const result = await mock.withTx((trx) => run(trx, { ...input, position: 99 }, ctx));

    expect(result.ok).toBe(true);
    expect(mock.inserts[0].insertValues()).toEqual(expect.objectContaining({ position: 3 }));
    expect(mock.updates.length).toBe(0);
  });

  it("inserts at a middle slot and renormalizes trailing sibling positions", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [basePipeline],
      [],
      [baseStage, inProgressStage],
      [{ ...doneStage, position: 1 }],
    );

    const result = await mock.withTx((trx) => run(trx, { ...input, position: 1 }, ctx));

    expect(result.ok).toBe(true);
    expect(mock.inserts[0].insertValues()).toEqual(expect.objectContaining({ position: 1 }));
    const shifted = mock.updates.map((u) => u.updateValues());
    expect(shifted).toEqual(
      expect.arrayContaining([
        expect.objectContaining({ position: 2 }),
        expect.objectContaining({ position: 3 }),
      ]),
    );
  });

  it("returns error when pipeline not found", 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(PipelineNotFoundError);
    }
  });

  it("returns error when pipeline is archived", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([archivedPipeline]);

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

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

  it("returns error when pipeline is locked", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([lockedPipeline]);

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

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

  it("returns error when name is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipeline]);

    const result = await mock.withTx((trx) => run(trx, { ...input, name: "" }, ctx));

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

  it("returns error when stage name duplicates another on the same pipeline", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipeline], [baseStage]);

    const result = await mock.withTx((trx) => run(trx, { ...input, name: baseStage.name }, ctx));

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

  it("returns error when category is invalid", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipeline], []);

    const result = await mock.withTx((trx) => run(trx, { ...input, category: "INVALID" }, ctx));

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