import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it, vi } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  DuplicatePipelineNameError,
  InvalidCategoryError,
  InvalidNameError,
  InvalidPipelineTypeError,
  UserNotFoundError,
} from "../lib/errors.generated";
import { basePipeline } from "../testing/fixtures";
import { run, type CreatePipelineInput } from "./createPipeline";

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

  const input = {
    name: basePipeline.name,
    description: basePipeline.description ?? undefined,
    pipelineType: basePipeline.pipelineType,
    createdByUserId: basePipeline.createdByUserId,
  } satisfies CreatePipelineInput;

  it("creates pipeline with valid name and creator", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([], [basePipeline]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.pipeline).toEqual(basePipeline);
    }
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({
        name: basePipeline.name,
        createdByUserId: basePipeline.createdByUserId,
        status: "ACTIVE",
      }),
    );
  });

  it("passes consumer extension fields through to the insert", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([], [basePipeline]);

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

    expect(result.ok).toBe(true);
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ workspaceId: "workspace-1" }),
    );
  });

  it("returns USER_NOT_FOUND when getUser dep returns null for createdByUserId", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const getUser = vi.fn().mockResolvedValue(null);

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

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(UserNotFoundError);
    }
    expect(getUser).toHaveBeenCalledWith(input.createdByUserId);
  });

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

    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 pipeline name already exists for the pipelineType", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipeline]);

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

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

  it("allows same pipeline name under a different pipelineType", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([], [{ ...basePipeline, id: "pipeline-2", pipelineType: "SUPPORT_QUEUE" }]);

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

    expect(result.ok).toBe(true);
  });

  it("returns INVALID_PIPELINE_TYPE when pipelineType is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

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

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

  it("returns INVALID_PIPELINE_TYPE when pipelineType is outside the injected vocabulary", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

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

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

  it("accepts any pipelineType when no vocabulary is injected", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([], [{ ...basePipeline, pipelineType: "CUSTOM_BOARD" }]);

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

    expect(result.ok).toBe(true);
  });

  it("allows duplicate names for locked pipelines (skips uniqueness check)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    // Even if a same-named locked Pipeline already exists, createPipeline must
    // succeed — managed-board identity is owned by the managing module, not Pipeline.
    mock.enqueueResults([
      {
        ...basePipeline,
        id: "pipeline-locked",
        locked: true,
      },
    ]);

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

    expect(result.ok).toBe(true);
  });

  it("seeds initial stages when stages input is supplied", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [
        {
          ...basePipeline,
          id: "pipeline-board",
          locked: true,
        },
      ],
      [],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          ...input,
          locked: true,
          stages: [
            { name: "Todo", category: "NOT_STARTED", color: "#3b82f6" },
            { name: "Doing", category: "IN_PROGRESS" },
            { name: "Done", category: "DONE", color: "#16a34a" },
          ],
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    // Second insert seeds the lane template onto the new pipeline.
    expect(mock.inserts[1].insertRows()).toEqual(
      expect.arrayContaining([
        expect.objectContaining({ name: "Todo", position: 1, category: "NOT_STARTED" }),
        expect.objectContaining({
          name: "Doing",
          position: 2,
          category: "IN_PROGRESS",
          color: null,
        }),
        expect.objectContaining({ name: "Done", position: 3, category: "DONE" }),
      ]),
    );
  });

  it("returns INVALID_CATEGORY when a seeded stage category is invalid", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          ...input,
          // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- intentionally invalid category for the error path
          stages: [{ name: "Todo", category: "NOT_A_CATEGORY" as never }],
        },
        ctx,
      ),
    );

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