#!/usr/bin/env bash

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEMPLATES_DIR="$(dirname "$SCRIPT_DIR")/templates"

echo -e "${BLUE}╔════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   Terraform Module Tester - Skill #13      ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════╝${NC}"
echo

# Check if terraform is installed
if ! command -v terraform &> /dev/null; then
    echo -e "${RED}✗ Terraform not found${NC}"
    exit 1
fi

# Counters
TOTAL=0
PASSED=0
FAILED=0

# Function to test a module
test_module() {
    local module_path="$1"
    local module_name=$(basename "$module_path")

    echo -e "${YELLOW}Testing: $module_name${NC}"

    TOTAL=$((TOTAL + 1))

    # Change to module directory
    cd "$module_path"

    # Test 1: Terraform format check
    if ! terraform fmt -check -recursive > /dev/null 2>&1; then
        echo -e "${RED}✗ Format check failed${NC}"
        FAILED=$((FAILED + 1))
        return
    fi

    # Test 2: Terraform init (backend=false)
    if ! terraform init -backend=false > /dev/null 2>&1; then
        echo -e "${RED}✗ Init failed${NC}"
        FAILED=$((FAILED + 1))
        return
    fi

    # Test 3: Terraform validate
    if ! terraform validate > /dev/null 2>&1; then
        echo -e "${RED}✗ Validation failed${NC}"
        FAILED=$((FAILED + 1))
        return
    fi

    # Cleanup
    rm -rf .terraform

    echo -e "${GREEN}✓ Passed${NC}"
    PASSED=$((PASSED + 1))
}

# Test all modules
echo -e "${BLUE}Testing all modules in templates/...${NC}"
echo

for module_dir in "$TEMPLATES_DIR"/*; do
    if [ -d "$module_dir" ]; then
        test_module "$module_dir"
    fi
done

# Summary
echo
echo -e "${BLUE}════════════════════════════════════════════${NC}"
echo -e "${BLUE}Test Summary${NC}"
echo -e "${BLUE}════════════════════════════════════════════${NC}"
echo "Total:  $TOTAL"
echo -e "${GREEN}Passed: $PASSED${NC}"
if [ $FAILED -gt 0 ]; then
    echo -e "${RED}Failed: $FAILED${NC}"
fi
echo

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}✓ All tests passed!${NC}"
    exit 0
else
    echo -e "${RED}✗ Some tests failed${NC}"
    exit 1
fi
