// ====== Form Validation ======

import { VALIDATION_RULES } from '../config/constants.js';

class ValidationManager {
    constructor() {
        this.rules = {
            required: (value) => ({
                isValid: value !== null && value !== undefined && value.toString().trim() !== '',
                message: 'This field is required'
            }),

            email: (value) => ({
                isValid: VALIDATION_RULES.EMAIL.test(value),
                message: 'Please enter a valid email address'
            }),

            minLength: (value, min) => ({
                isValid: value.length >= min,
                message: `Must be at least ${min} characters long`
            }),

            maxLength: (value, max) => ({
                isValid: value.length <= max,
                message: `Must be no more than ${max} characters long`
            }),

            password: (value) => {
                const strength = this.checkPasswordStrength(value);
                return {
                    isValid: strength.score >= 3, // At least medium strength
                    message: 'Password is too weak',
                    details: strength
                };
            },

            phone: (value) => ({
                isValid: VALIDATION_RULES.PHONE.test(value.replace(/\s/g, '')),
                message: 'Please enter a valid phone number'
            }),

            url: (value) => ({
                isValid: /^https?:\/\/.+\..+/.test(value),
                message: 'Please enter a valid URL'
            }),

            numeric: (value) => ({
                isValid: !isNaN(parseFloat(value)) && isFinite(value),
                message: 'Must be a number'
            }),

            match: (value, fieldName, form) => {
                const otherField = form.querySelector(`[name="${fieldName}"]`);
                return {
                    isValid: otherField && value === otherField.value,
                    message: 'Fields do not match'
                };
            }
        };
    }

    async validateField(value, ruleString, field) {
        const rules = ruleString.split('|');
        const errors = [];
        const form = field.closest('form');

        for (const rule of rules) {
            const [ruleName, param] = rule.split(':');
            
            if (this.rules[ruleName]) {
                const result = this.rules[ruleName](value, param, form);
                
                if (!result.isValid) {
                    errors.push(result.message);
                }
            }
        }

        return {
            isValid: errors.length === 0,
            errors
        };
    }

    checkPasswordStrength(password) {
        const checks = {
            length: password.length >= VALIDATION_RULES.PASSWORD.MIN_LENGTH,
            uppercase: VALIDATION_RULES.PASSWORD.REQUIRE_UPPERCASE ? /[A-Z]/.test(password) : true,
            lowercase: VALIDATION_RULES.PASSWORD.REQUIRE_LOWERCASE ? /[a-z]/.test(password) : true,
            number: VALIDATION_RULES.PASSWORD.REQUIRE_NUMBER ? /\d/.test(password) : true,
            special: VALIDATION_RULES.PASSWORD.REQUIRE_SPECIAL ? /[!@#$%^&*(),.?":{}|<>]/.test(password) : true
        };

        const score = Object.values(checks).filter(Boolean).length;
        
        return {
            score,
            checks,
            strength: score <= 2 ? 'weak' : score <= 3 ? 'medium' : score <= 4 ? 'strong' : 'very-strong'
        };
    }

    addRule(name, validator) {
        this.rules[name] = validator;
    }

    // Async validation for checking unique usernames, emails, etc.
    async validateUnique(value, field, endpoint) {
        try {
            const response = await fetch(`${endpoint}?${field}=${encodeURIComponent(value)}`);
            const data = await response.json();
            
            return {
                isValid: !data.exists,
                message: `${field} already exists`
            };
        } catch (error) {
            return {
                isValid: true, // Assume valid if check fails
                message: 'Validation check failed'
            };
        }
    }
}

// Create singleton instance
export const validation = new ValidationManager();