#!/bin/bash

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

echo -e "${BLUE}==============================================${NC}"
echo -e "${GREEN}      Production Readiness Checklist          ${NC}"
echo -e "${BLUE}==============================================${NC}"

# 1. Check PHP Version
PHP_VER=$(php -r 'echo PHP_VERSION;')
echo -ne "Checking PHP Version (8.2+ required)... "
if [[ $(echo "$PHP_VER 8.2" | awk '{print ($1 >= $2)}') -eq 1 ]]; then
    echo -e "${GREEN}OK ($PHP_VER)${NC}"
else
    echo -e "${RED}FAIL ($PHP_VER)${NC}"
fi

# 2. Check PHP Extensions
echo -e "\nChecking PHP Extensions:"
EXTENSIONS=("pgsql" "redis" "curl" "mbstring" "xml" "zip" "bcmath" "intl" "gd")
for ext in "${EXTENSIONS[@]}"; do
    echo -ne "  - $ext... "
    if php -m | grep -qi "$ext"; then
        echo -e "${GREEN}INSTALLED${NC}"
    else
        echo -e "${RED}MISSING${NC}"
    fi
done

# 3. Check .env settings
echo -e "\nChecking .env settings:"
if [ -f .env ]; then
    APP_ENV=$(grep APP_ENV .env | cut -d '=' -f2)
    APP_DEBUG=$(grep APP_DEBUG .env | cut -d '=' -f2)
    
    echo -ne "  - APP_ENV... "
    if [[ "$APP_ENV" == "production" ]]; then
        echo -e "${GREEN}production${NC}"
    else
        echo -e "${YELLOW}$APP_ENV (Warning: not production)${NC}"
    fi

    echo -ne "  - APP_DEBUG... "
    if [[ "$APP_DEBUG" == "false" ]]; then
        echo -e "${GREEN}false${NC}"
    else
        echo -e "${RED}true (CRITICAL: Disable debug in production!)${NC}"
    fi
else
    echo -e "${RED}.env file missing!${NC}"
fi

# 4. Check Directory Permissions
echo -e "\nChecking Directory Permissions:"
DIRS=("storage" "bootstrap/cache")
for dir in "${DIRS[@]}"; do
    echo -ne "  - $dir writable... "
    if [ -w "$dir" ]; then
        echo -e "${GREEN}YES${NC}"
    else
        echo -e "${RED}NO${NC}"
    fi
done

# 5. Check Mobile API URL
echo -e "\nChecking Mobile API Configuration:"
if [ -f mobile/services/api.ts ]; then
    if grep -q "Constants.expoConfig?.extra?.apiUrl" mobile/services/api.ts; then
        echo -e "${GREEN}Flexible (Production Ready)${NC}"
    else
        echo -e "${YELLOW}Hardcoded (Check mobile/services/api.ts)${NC}"
    fi
fi

# 6. Check Database Connectivity
echo -e "\nChecking Database Connectivity... "
php artisan db:monitor --quiet > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo -e "${GREEN}CONNECTED${NC}"
else
    echo -e "${RED}FAILED${NC}"
fi

echo -e "\n${BLUE}==============================================${NC}"
echo -e "${YELLOW}Next Steps for Smooth Deployment:${NC}"
echo -e "1. Run ${BLUE}php artisan optimize${NC} in production."
echo -e "2. Run ${BLUE}npm run build${NC} for frontend assets."
echo -e "3. Ensure ${BLUE}Supervisor${NC} is running for Queue and Reverb."
echo -e "4. Check ${BLUE}Nginx${NC} logs for any proxy issues."
echo -e "${BLUE}==============================================${NC}"
