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

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

  it("updates stage name", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseStage],
      [basePipeline],
      [],
      [{ ...baseStage, name: "Updated PipelineStage" }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { stageId: baseStage.id, name: "Updated PipelineStage" }, ctx),
    );

    expect(result.ok).toBe(true);
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({ name: "Updated PipelineStage" }),
    );
  });

  it("updates stage category", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseStage], [basePipeline], [{ ...baseStage, category: "IN_PROGRESS" }]);

    const result = await mock.withTx((trx) =>
      run(trx, { stageId: baseStage.id, category: "IN_PROGRESS" }, ctx),
    );

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

  it("updates stage color", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseStage], [basePipeline], [{ ...baseStage, color: null }]);

    const result = await mock.withTx((trx) =>
      run(trx, { stageId: baseStage.id, color: null }, ctx),
    );

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

  it("returns error when stage not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { stageId: "missing-stage" }, ctx));

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

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

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

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

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

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

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

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

    const result = await mock.withTx((trx) =>
      run(trx, { stageId: baseStage.id, name: inProgressStage.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([baseStage], [basePipeline]);

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

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

  it("passes extension fields through but strips reserved model columns", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const input = {
      stageId: baseStage.id,
      wipLimit: 5,
      position: 99,
      pipelineId: "spoofed-pipeline",
      id: "spoofed-id",
    };
    mock.enqueueResults([baseStage], [basePipeline], [baseStage]);

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

    expect(result.ok).toBe(true);
    const values = mock.updates[0].updateValues();
    expect(values).toEqual(expect.objectContaining({ wipLimit: 5 }));
    expect(values).not.toHaveProperty("position");
    expect(values).not.toHaveProperty("pipelineId");
    expect(values).not.toHaveProperty("id");
  });
});
