#!/bin/bash
#
# MySQL 5.7 Compatibility Verification Script
# Checks migrations for MySQL 5.7 incompatible syntax
#
# Usage: ./scripts/verify-mysql57-compatibility.sh

set -e

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

echo "============================================"
echo "MySQL 5.7 Compatibility Check"
echo "============================================"
echo ""

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

ISSUES_FOUND=0

# Check 1: JSON default values (not supported in MySQL 5.7)
echo -e "${YELLOW}Checking for JSON default values...${NC}"
JSON_DEFAULTS=$(grep -rn "->json.*->default" database/migrations/ || true)
if [ -n "$JSON_DEFAULTS" ]; then
    echo -e "${RED}⚠ Found JSON columns with default values (incompatible with MySQL 5.7):${NC}"
    echo "$JSON_DEFAULTS"
    echo "Fix: Remove ->default('{}') from JSON columns"
    ISSUES_FOUND=$((ISSUES_FOUND + 1))
else
    echo -e "${GREEN}✓ No JSON default values found${NC}"
fi
echo ""

# Check 2: Arrow operator in queries (MySQL 5.7 uses JSON_EXTRACT)
echo -e "${YELLOW}Checking for JSON arrow operators in queries...${NC}"
JSON_ARROWS=$(grep -rn '\->' app/ tests/ --include="*.php" | grep -v "//\|/\*" | grep "json\|metadata" || true)
if [ -n "$JSON_ARROWS" ]; then
    echo -e "${YELLOW}⚠ Found possible JSON arrow operators (may not work in MySQL 5.7):${NC}"
    echo "$JSON_ARROWS" | head -20
    echo "Review these manually. Use JSON_EXTRACT() for MySQL 5.7 compatibility"
else
    echo -e "${GREEN}✓ No obvious JSON arrow operators found${NC}"
fi
echo ""

# Check 3: Unsigned big integers (check compatibility)
echo -e "${YELLOW}Checking migration syntax...${NC}"
BIGINT_UNSIGNED=$(grep -rn "unsignedBigInteger" database/migrations/ || true)
if [ -n "$BIGINT_UNSIGNED" ]; then
    echo -e "${GREEN}✓ Found $(echo "$BIGINT_UNSIGNED" | wc -l | tr -d ' ') unsignedBigInteger columns (compatible)${NC}"
else
    echo -e "${GREEN}✓ No unsignedBigInteger columns (that's fine)${NC}"
fi
echo ""

# Summary
echo "============================================"
if [ $ISSUES_FOUND -eq 0 ]; then
    echo -e "${GREEN}✓ No MySQL 5.7 compatibility issues found${NC}"
else
    echo -e "${RED}⚠ Found $ISSUES_FOUND potential compatibility issues${NC}"
    echo "Review the output above and fix issues before deploying"
fi
echo "============================================"
echo ""

exit $ISSUES_FOUND
