/** 字段名 code 规范：字母或下划线开头，仅含字母、数字、下划线 */
export const FIELD_NAME_CODE_PATTERN = /^[a-zA-Z_]\w*$/;

export type FieldNameErrorKey =
  | 'fieldNameDuplicate'
  | 'fieldNameInvalidFormat'
  | 'fieldNameRequired';

export interface FieldNameValidateResult {
  valid: boolean;
  errorKey?: FieldNameErrorKey;
  duplicateName?: string;
}

/** 规范化字段名：去除空格与非法字符，数字开头时补下划线 */
export function sanitizeFieldNameCode(name: string): string {
  let result = name.replaceAll(/\s/g, '').replaceAll(/[^\w]/g, '');
  if (result && /^\d/.test(result)) {
    result = `_${result}`;
  }
  return result;
}

/** 失焦时规范化：若仅含非法字符则保留原值，避免被清空后误报「不能为空」 */
export function normalizeFieldNameOnBlur(name: string): string {
  const trimmed = name.trim();
  if (!trimmed) {
    return '';
  }

  const sanitized = sanitizeFieldNameCode(name);
  if (!sanitized) {
    return trimmed;
  }

  return sanitized;
}

/** 校验单个字段名是否符合 code 规范 */
export function validateFieldNameCode(name: string): FieldNameValidateResult {
  const trimmed = name.trim();
  if (!trimmed) {
    return { valid: false, errorKey: 'fieldNameRequired' };
  }
  if (!FIELD_NAME_CODE_PATTERN.test(trimmed)) {
    return { valid: false, errorKey: 'fieldNameInvalidFormat' };
  }
  return { valid: true };
}

/** 校验字段名列表（格式 + 重复） */
export function validateFieldNameList(names: string[]): FieldNameValidateResult {
  const seen = new Set<string>();

  for (const rawName of names) {
    const result = validateFieldNameCode(rawName);
    if (!result.valid) {
      return result;
    }

    const name = rawName.trim();
    if (seen.has(name)) {
      return {
        valid: false,
        errorKey: 'fieldNameDuplicate',
        duplicateName: name,
      };
    }
    seen.add(name);
  }

  return { valid: true };
}
