export interface ValidationRule {
    validate: (value: unknown) => boolean;
    message: string;
}

export interface ValidationResult {
    isValid: boolean;
    errors: Record<string, string>;
}

export abstract class FormValidator<T> {
    protected rules: Map<keyof T, ValidationRule[]> = new Map();

    public validate(data: T): ValidationResult {
        const errors: Record<string, string> = {};

        for (const [field, rules] of this.rules.entries()) {
            const value = data[field];
            for (const rule of rules) {
                if (!rule.validate(value)) {
                    errors[field as string] = rule.message;
                    break;
                }
            }
        }

        return {
            isValid: Object.keys(errors).length === 0,
            errors
        };
    }

    public displayErrors(errors: Record<string, string>): void {
        document.querySelectorAll('.validation-error').forEach(el => el.remove());

        for (const [field, message] of Object.entries(errors)) {
            const input = document.querySelector<HTMLInputElement>(`[name="${field}"]`);
            if (input) {
                const errorEl = document.createElement('div');
                errorEl.className = 'validation-error';
                errorEl.textContent = message;
                errorEl.style.cssText = 'color: red; font-size: 12px; margin-top: 4px;';
                input.parentElement?.appendChild(errorEl);
            }
        }
    }
}
