import type { PluginConfig } from "./types.js";

const DEFAULT_CONFIG: PluginConfig = {
  defaultLimit: 8,
  maxLimit: 15,
};

export function resolvePluginConfig(value: unknown): PluginConfig {
  if (!value || typeof value !== "object") {
    return DEFAULT_CONFIG;
  }

  const candidate = value as Partial<Record<keyof PluginConfig, unknown>>;
  const defaultLimit = normalizeLimit(
    candidate.defaultLimit,
    DEFAULT_CONFIG.defaultLimit,
  );
  const maxLimit = normalizeLimit(candidate.maxLimit, DEFAULT_CONFIG.maxLimit);

  return {
    defaultLimit: Math.min(defaultLimit, maxLimit),
    maxLimit,
  };
}

export function clampRequestedLimit(
  limit: unknown,
  config: PluginConfig,
): number {
  const normalized = normalizeLimit(limit, config.defaultLimit);
  return Math.max(1, Math.min(normalized, config.maxLimit));
}

function normalizeLimit(value: unknown, fallback: number): number {
  if (typeof value === "number" && Number.isInteger(value) && value > 0) {
    return value;
  }

  return fallback;
}
