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 {
  DuplicateLabelNameError,
  InvalidNameError,
  PipelineArchivedError,
  PipelineNotFoundError,
} from "../lib/errors.generated";
import { archivedPipeline, baseLabel, basePipeline } from "../testing/fixtures";
import { run } from "./createPipelineLabel";

describe("createPipelineLabel", () => {
  const ctx: CommandContext = {
    actorId: "user-1",
    permissions: ["pipeline-management:label:createPipelineLabel"],
  };

  const input = {
    pipelineId: basePipeline.id,
    name: "urgent",
    color: "#EF4444",
    description: "Items requiring urgent attention",
  };

  it("creates a label on an active pipeline", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipeline], [], [baseLabel]);

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

    expect(result.ok).toBe(true);
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({
        pipelineId: input.pipelineId,
        name: input.name,
        color: input.color,
        description: input.description,
      }),
    );
  });

  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, pipelineId: archivedPipeline.id }, ctx),
    );

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

  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 label name duplicates another on the same pipeline", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipeline], [baseLabel]);

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

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