#!/bin/bash

# Load environment variables from current directory
if [ ! -f .env ]; then
    echo "Error: .env file not found in current directory!"
    exit 1
fi

source .env

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

# Function to check if a command was successful
check_status() {
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ $1${NC}"
        return 0
    else
        echo -e "${RED}✗ $1${NC}"
        return 1
    fi
}

echo -e "${YELLOW}Starting basic environment verification...${NC}"

# Check if containers are running
echo "Checking Docker containers..."
if ! docker-compose ps | grep -q "wordpress.*Up"; then
    echo -e "${RED}WordPress container is not running${NC}"
    exit 1
fi
if ! docker-compose ps | grep -q "db.*Up"; then
    echo -e "${RED}Database container is not running${NC}"
    exit 1
fi
check_status "Container status check"

# Check database connection
echo "Verifying database connection..."
if ! docker-compose exec db mysql -u"$DEV_DB_USER" -p"$DEV_DB_PASSWORD" -e "SELECT 1;" > /dev/null 2>&1; then
    echo -e "${RED}Database connection failed${NC}"
    exit 1
fi
check_status "Database connection"

# Verify WordPress installation
echo "Verifying WordPress installation..."
if ! docker-compose exec wordpress wp core is-installed --allow-root; then
    echo -e "${RED}WordPress is not properly installed${NC}"
    exit 1
fi
check_status "WordPress installation"

# Test homepage accessibility
echo "Testing homepage accessibility..."
if ! curl -s -I "http://localhost:8080" | grep -q "200 OK"; then
    echo -e "${RED}Homepage is not accessible${NC}"
    exit 1
fi
check_status "Homepage accessibility"

echo -e "${GREEN}Basic environment verification completed successfully!${NC}"