#!/usr/bin/env bash
# Validate all configuration files
# Checks JSON, YAML, and TOML files for validity

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

source "$SCRIPT_DIR/../lib/init.sh"
source "$SCRIPT_DIR/../lib/common/validation.sh"

cd "$PROJECT_ROOT"

log_section "Configuration Validation"

errors=0

# Validate JSON files
log_subsection "Validating JSON files"
while IFS= read -r -d '' file; do
    if ! validate_json "$file"; then
        ((errors++)) || true
    fi
done < <(find config -name "*.json" -type f -print0 2>/dev/null)

# Validate YAML files
log_subsection "Validating YAML files"
while IFS= read -r -d '' file; do
    if ! validate_yaml "$file"; then
        ((errors++)) || true
    fi
done < <(find . -name "*.yml" -o -name "*.yaml" -type f -print0 2>/dev/null | grep -v node_modules | grep -v .terraform)

# Validate TOML files
log_subsection "Validating TOML files"
while IFS= read -r -d '' file; do
    if ! validate_toml "$file"; then
        ((errors++)) || true
    fi
done < <(find config -name "*.toml" -type f -print0 2>/dev/null)

if [ $errors -eq 0 ]; then
    log_success "All configuration files are valid"
    exit 0
else
    log_error "Found $errors configuration file errors"
    exit 1
fi

