import type {
  Cell,
  CellBorder,
  ValidationResult,
  ValidationRule,
} from './types';

export function cellKey(rowKey: string, columnId: string): string {
  return `${rowKey}:${columnId}`;
}

export function parseCellKey(key: string): Cell | null {
  const idx = key.indexOf(':');
  if (idx === -1) {
    return null;
  }
  return { rowKey: key.slice(0, idx), columnId: key.slice(idx + 1) };
}

export const noBorder: CellBorder = {
  top: false,
  bottom: false,
  left: false,
  right: false,
};

export const validResult: ValidationResult = { valid: true };

function checkValidationRule(rule: ValidationRule, value: any): boolean {
  switch (rule.type) {
    case 'required':
      return value != null && value !== '';
    case 'min':
      return typeof value === 'number' && value >= rule.value;
    case 'max':
      return typeof value === 'number' && value <= rule.value;
    case 'minLength':
      return typeof value === 'string' && value.length >= rule.value;
    case 'maxLength':
      return typeof value === 'string' && value.length <= rule.value;
    case 'pattern':
      return typeof value === 'string' && rule.value.test(value);
    case 'custom':
      return rule.validate(value);
    default:
      return true;
  }
}

export function runCellValidation(
  value: any,
  rules?: ValidationRule[],
  typeValidate?: (value: any, rules?: ValidationRule[]) => string | null,
): ValidationResult {
  const errors: string[] = [];

  if (rules) {
    for (const rule of rules) {
      if (!checkValidationRule(rule, value)) {
        errors.push(rule.message);
      }
    }
  }

  if (typeValidate) {
    const typeError = typeValidate(value, rules);
    if (typeError) {
      errors.push(typeError);
    }
  }

  return errors.length === 0 ? validResult : { valid: false, errors };
}
