import type { Transaction } from "@tailor-platform/sdk/kysely";
import { logger } from "@tailor-platform/function-logger";
import type { Result } from "./result";
import type { CommandContext } from "./types";
import { requirePermission } from "./requirePermission";
import type { InsufficientPermissionError } from "./errors";

export type Command<TInput, TReturn extends Result<unknown, Error>> = (
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  db: Transaction<any>,
  input: TInput,
  ctx: CommandContext,
) => Promise<TReturn>;

type CommandResult<TReturn extends Result<unknown, Error>> =
  | TReturn
  | Result<never, InstanceType<typeof InsufficientPermissionError>>;

export function defineCommand<
  TDeps extends unknown[],
  TInput,
  TReturn extends Result<unknown, Error>,
>(
  name: string,
  permission: string,
  impl: (
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    db: Transaction<any>,
    input: TInput,
    ctx: CommandContext,
    ...deps: TDeps
  ) => Promise<TReturn>,
): (...deps: TDeps) => Command<TInput, CommandResult<TReturn>> {
  return (...deps) =>
    async (db, input, ctx) => {
      if (!db.isTransaction) {
        throw new Error("Commands require a transaction database");
      }
      const check = requirePermission(ctx, permission);
      if (!check.ok) {
        logger.debug(`[command:${name}] permission denied`);
        return check;
      }
      logger.debug(`[command:${name}] start`, { input });
      const start = Date.now();
      const result = await impl(db, input, ctx, ...deps);
      const ms = Date.now() - start;
      if ("ok" in result && !result.ok) {
        logger.debug(`[command:${name}] error (${ms}ms)`, {
          error: result.error,
        });
      } else {
        logger.debug(`[command:${name}] ok (${ms}ms)`);
      }
      return result;
    };
}
