#!/bin/bash
# Script to fetch verification code from Django database
# Usage: ./get_verification_code.sh <email>
# Output: Writes the verification code to /tmp/mycrib_verification_code_<sanitized_email>.txt

EMAIL="$1"

if [ -z "$EMAIL" ]; then
    echo "Usage: $0 <email>"
    exit 1
fi

# Sanitize email for filename
SANITIZED_EMAIL=$(echo "$EMAIL" | sed 's/@/_at_/g' | sed 's/\./_dot_/g')
OUTPUT_FILE="/tmp/mycrib_verification_code_${SANITIZED_EMAIL}.txt"

cd /Users/treyt/Desktop/code/MyCrib/myCribAPI

# Try docker exec first (if running in Docker)
if docker ps --format '{{.Names}}' | grep -q 'mycrib-web\|myCrib-web'; then
    CONTAINER_NAME=$(docker ps --format '{{.Names}}' | grep -E 'mycrib-web|myCrib-web' | head -1)
    CODE=$(docker exec "$CONTAINER_NAME" python manage.py shell -c "
from user.models import ConfirmationCode
from django.contrib.auth import get_user_model
User = get_user_model()
try:
    user = User.objects.get(email='$EMAIL')
    code = ConfirmationCode.objects.filter(user=user, is_used=False).latest('created_at')
    print(code.code)
except Exception as e:
    print('ERROR:', e)
" 2>/dev/null)
else
    # Fallback to local Python
    export DJANGO_SETTINGS_MODULE=myCrib.settings
    CODE=$(python manage.py shell -c "
from user.models import ConfirmationCode
from django.contrib.auth import get_user_model
User = get_user_model()
try:
    user = User.objects.get(email='$EMAIL')
    code = ConfirmationCode.objects.filter(user=user, is_used=False).latest('created_at')
    print(code.code)
except Exception as e:
    print('ERROR:', e)
" 2>/dev/null)
fi

# Check if we got a valid 6-digit code
if [[ "$CODE" =~ ^[0-9]{6}$ ]]; then
    echo "$CODE" > "$OUTPUT_FILE"
    echo "Verification code saved to $OUTPUT_FILE: $CODE"
    exit 0
else
    echo "Failed to get verification code: $CODE"
    exit 1
fi
