import type { ToolInputResult } from '../agent-tool.types';

const FORBIDDEN_KEYS = new Set([
  'userId', 'isSuperAdmin', 'permissions', 'roles', 'ability', 'user', 'password', 'token',
]);

export function rejectUnknownKeys(
  input: Record<string, unknown>,
  allowed: readonly string[],
): ToolInputResult<never> | undefined {
  const allowedSet = new Set(allowed);
  for (const key of Object.keys(input)) {
    if (FORBIDDEN_KEYS.has(key) || !allowedSet.has(key)) {
      return { ok: false, error: `不允许的输入字段: ${key}` };
    }
  }
  return undefined;
}

export function optionalString(
  value: unknown,
  field: string,
  maxLength: number,
): ToolInputResult<string | undefined> {
  if (value === undefined) return { ok: true, value: undefined };
  if (typeof value !== 'string' || value.length > maxLength) {
    return { ok: false, error: `${field} 必须是长度不超过${maxLength}的字符串` };
  }
  return { ok: true, value: value.trim() || undefined };
}

export function optionalPositiveInt(
  value: unknown,
  field: string,
  maximum?: number,
): ToolInputResult<number | undefined> {
  if (value === undefined) return { ok: true, value: undefined };
  const parsed = Number(value);
  if (!Number.isInteger(parsed) || parsed <= 0 || (maximum !== undefined && parsed > maximum)) {
    return { ok: false, error: `${field} 必须是正整数${maximum ? `且不超过${maximum}` : ''}` };
  }
  return { ok: true, value: parsed };
}

export function optionalDate(value: unknown, field: string): ToolInputResult<string | undefined> {
  if (value === undefined) return { ok: true, value: undefined };
  if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) {
    return { ok: false, error: `${field} 必须是 YYYY-MM-DD 日期` };
  }
  const date = new Date(`${value}T00:00:00Z`);
  if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value) {
    return { ok: false, error: `${field} 不是有效日期` };
  }
  return { ok: true, value };
}
