/**
 * Validation Error Extraction Utility
 *
 * Centralizes the logic for extracting structured validation errors
 * from additionalData to avoid duplication across handlers.
 */

export interface ValidationError {
	field: string;
	code: string;
	message: { vi: string; en: string };
}

export type ValidationErrors = ValidationError[];

/**
 * Extract structured validation errors from additionalData
 * @param additionalData - The additionalData object from an error
 * @returns Validation errors array if found, null otherwise
 */
export function extractValidationErrors(additionalData: unknown): ValidationErrors | null {
	if (additionalData && typeof additionalData === 'object') {
		if ('errors' in additionalData) {
			const errors = (additionalData as any).errors;
			if (Array.isArray(errors)) {
				return errors;
			}
		}
	}
	return null;
}

/**
 * Get the first error code from validation errors
 * @param additionalData - The additionalData object from an error
 * @returns First error code if validation errors exist, null otherwise
 */
export function getFirstErrorCode(additionalData: unknown): string | null {
	const validationErrors = extractValidationErrors(additionalData);
	if (validationErrors && validationErrors.length > 0 && validationErrors[0]?.code) {
		return validationErrors[0].code;
	}
	return null;
}
