/**
 * Get First Validation Error
 *
 * Extracts the first error from react-hook-form FieldErrors,
 * including support for nested errors (e.g., model_params.temperature).
 *
 * @module lib/forms/utils/getFirstValidationError
 */

import type { FieldErrors, FieldValues } from 'react-hook-form';

export interface ValidationError {
  /** Field path (e.g., 'name' or 'model_params.temperature') */
  field: string;
  /** Error message */
  message: string;
}

/**
 * Recursively extract the first error from FieldErrors
 *
 * @param errors - FieldErrors object from react-hook-form
 * @param prefix - Current field path prefix for nested errors
 * @returns First validation error found, or null if no errors
 *
 * @example
 * ```ts
 * const errors = { model_params: { temperature: { message: 'Required' } } };
 * const error = getFirstValidationError(errors);
 * // { field: 'model_params.temperature', message: 'Required' }
 * ```
 */
export function getFirstValidationError<T extends FieldValues>(
  errors: FieldErrors<T>,
  prefix = ''
): ValidationError | null {
  for (const key of Object.keys(errors)) {
    const error = errors[key as keyof typeof errors];
    if (!error || typeof error !== 'object') continue;

    const fieldPath = prefix ? `${prefix}.${key}` : key;

    // Check if this is a direct error with a message
    if ('message' in error && typeof error.message === 'string') {
      return { field: fieldPath, message: error.message };
    }

    // Check if this is a nested object (e.g., model_params.temperature)
    const nestedError = getFirstValidationError(error as FieldErrors<FieldValues>, fieldPath);
    if (nestedError) return nestedError;
  }

  return null;
}

/**
 * Get all validation errors as a flat array
 *
 * @param errors - FieldErrors object from react-hook-form
 * @param prefix - Current field path prefix for nested errors
 * @returns Array of all validation errors
 */
export function getAllValidationErrors<T extends FieldValues>(
  errors: FieldErrors<T>,
  prefix = ''
): ValidationError[] {
  const result: ValidationError[] = [];

  for (const key of Object.keys(errors)) {
    const error = errors[key as keyof typeof errors];
    if (!error || typeof error !== 'object') continue;

    const fieldPath = prefix ? `${prefix}.${key}` : key;

    if ('message' in error && typeof error.message === 'string') {
      result.push({ field: fieldPath, message: error.message });
    } else {
      // Nested object without message, recurse
      result.push(...getAllValidationErrors(error as FieldErrors<FieldValues>, fieldPath));
    }
  }

  return result;
}
