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 { CommentNotFoundError, ForbiddenError, InvalidBodyError } from "../lib/errors.generated";
import { basePipelineItemComment } from "../testing/fixtures";
import { run } from "./updatePipelineItemComment";

describe("updatePipelineItemComment", () => {
  const ctx: CommandContext = {
    actorId: basePipelineItemComment.authorUserId,
    permissions: ["pipeline-management:pipelineItemComment:updatePipelineItemComment"],
  };

  const input = {
    commentId: basePipelineItemComment.id,
    body: "Updated body",
  };

  it("author can update the body of their own comment", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [basePipelineItemComment],
      [{ ...basePipelineItemComment, body: input.body }],
    );

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

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

  it("updatedAt advances to the current timestamp on success", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [basePipelineItemComment],
      [{ ...basePipelineItemComment, body: input.body, updatedAt: new Date() }],
    );

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

    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({ updatedAt: expect.any(Date) as unknown as Date }),
    );
  });

  it("returns error when comment does not exist", 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(CommentNotFoundError);
    }
  });

  it("non-author update is rejected with FORBIDDEN", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipelineItemComment]);

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

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

  it("empty body update is rejected with INVALID_BODY", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipelineItemComment]);

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

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

  it("passes extension fields through but strips reserved model columns", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const reservedInput = {
      ...input,
      editedReason: "typo",
      authorUserId: "spoofed-author",
      itemId: "spoofed-item",
      id: "spoofed-id",
    };
    mock.enqueueResults([basePipelineItemComment], [basePipelineItemComment]);

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

    expect(result.ok).toBe(true);
    const values = mock.updates[0].updateValues();
    expect(values).toEqual(expect.objectContaining({ editedReason: "typo" }));
    expect(values).not.toHaveProperty("authorUserId");
    expect(values).not.toHaveProperty("itemId");
    expect(values).not.toHaveProperty("id");
  });
});
