import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { expect } from "vitest";
import type { Command } from "../shared/defineCommand";
import { InsufficientPermissionError } from "../shared/errors";
import type { Result, ErrorOf, ValueOf } from "../shared/result";
import type { CommandContext } from "../shared/types";

export function testNotFound<TInput, TReturn extends Result<unknown, Error>>(
  command: Command<TInput, TReturn>,
  input: TInput,
  expectedError: abstract new (...args: never[]) => ErrorOf<TReturn>,
) {
  return async () => {
    const mock = createKyselyMock();
    const ctx: CommandContext = { actorId: "test-actor", permissions: [] };
    const result = await mock.withTx((trx) => command(trx, input, ctx));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(expectedError);
    }
  };
}

export function testPermissionDenied<TInput, TReturn extends Result<unknown, Error>>(
  command: Command<TInput, TReturn>,
  input: TInput,
) {
  return async () => {
    const mock = createKyselyMock();
    const denied: CommandContext = { actorId: "test-actor", permissions: [] };
    const result = await mock.withTx((trx) => command(trx, input, denied));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InsufficientPermissionError);
    }
  };
}

export function testIdempotent<
  TInput,
  TReturn extends Result<Record<string, unknown>, Error>,
  TKey extends string & keyof ValueOf<TReturn>,
>(
  command: Command<TInput, TReturn>,
  input: TInput,
  existingEntity: Record<string, unknown>,
  entityKey: TKey,
) {
  return async () => {
    const mock = createKyselyMock();
    mock.setQueryResolver((query) => (query.kind === "SelectQueryNode" ? [existingEntity] : []));
    const ctx: CommandContext = { actorId: "test-actor", permissions: [] };
    const result = await mock.withTx((trx) => command(trx, input, ctx));
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value[entityKey]).toEqual(existingEntity);
    }
    expect(mock.updates).toHaveLength(0);
  };
}
