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 {
  PipelineNotFoundError,
  DuplicatePipelineNameError,
  InvalidNameError,
} from "../lib/errors.generated";
import { basePipeline } from "../testing/fixtures";
import { run } from "./updatePipeline";

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

  it("updates pipeline name", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const input = { pipelineId: basePipeline.id, name: "Updated Pipeline" };
    mock.enqueueResults([basePipeline], [], [{ ...basePipeline, name: "Updated Pipeline" }]);

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

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

  it("updates pipeline description", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const input = { pipelineId: basePipeline.id, description: null };
    mock.enqueueResults([basePipeline], [{ ...basePipeline, description: null }]);

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

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

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

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

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

  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, { pipelineId: basePipeline.id, name: "" }, ctx),
    );

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

  it("returns error when name duplicates another pipeline of the same pipelineType", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [basePipeline],
      [{ ...basePipeline, id: "pipeline-2", name: "Other Pipeline" }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { pipelineId: basePipeline.id, name: "Other Pipeline" }, ctx),
    );

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

  it("passes extension fields through but strips reserved model columns", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const input = {
      pipelineId: basePipeline.id,
      teamId: "team-1",
      locked: true,
      status: "ARCHIVED",
      id: "spoofed-id",
      itemNumberSeq: 999,
    };
    mock.enqueueResults([basePipeline], [basePipeline]);

    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({ teamId: "team-1" }));
    expect(values).not.toHaveProperty("locked");
    expect(values).not.toHaveProperty("status");
    expect(values).not.toHaveProperty("id");
    expect(values).not.toHaveProperty("itemNumberSeq");
  });

  it("allows renaming a locked pipeline to a name already used by another locked pipeline", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const lockedPipeline = { ...basePipeline, locked: true } as const;
    mock.enqueueResults([lockedPipeline], [{ ...lockedPipeline, name: "Maintenance" }]);

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

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