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

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

  const input = {
    itemId: baseItem.id,
    body: "Looks good to me",
  };

  it("creating a comment with a valid body and existing item succeeds", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItem], [basePipelineItemComment]);

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

    expect(result.ok).toBe(true);
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({
        itemId: baseItem.id,
        body: input.body,
        authorUserId: ctx.actorId,
      }),
    );
  });

  it("createdAt is set automatically at creation time", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItem], [basePipelineItemComment]);

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

    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ createdAt: expect.any(Date) as unknown as Date }),
    );
  });

  it("returns error when item 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(ItemNotFoundError);
    }
  });

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

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

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