#!/usr/bin/env bash
set -e
cd /var/www/html/vocabapi

PLAIN="${1:-Japherlim01}"

echo "=== Current mail_password row ==="
php artisan tinker --execute='$c=\App\Models\Config::where("key","mail_password")->first(); echo "id=".$c->id." type=".$c->type." stored_len=".strlen($c->getRawOriginal("value")), PHP_EOL, "decrypts_to_plain=".($c->value === "Japherlim01" ? "YES" : "no") . PHP_EOL;' 2>&1

echo ""
echo "=== Re-encrypting with prod APP_KEY ==="
# Use the model mutator (encrypts when type=password). Saves the row.
php artisan tinker --execute='$c=\App\Models\Config::where("key","mail_password")->first(); $c->value = "'"$PLAIN"'"; $c->save(); echo "saved, new stored_len=".strlen($c->getRawOriginal("value")) . PHP_EOL;' 2>&1

echo ""
echo "=== Verify decrypt now returns plain text ==="
php artisan tinker --execute='$c=\App\Models\Config::where("key","mail_password")->first(); echo "decrypts_to_plain=".($c->fresh()->value === "'"$PLAIN"'" ? "YES" : "no") . PHP_EOL;' 2>&1

echo ""
echo "=== Clear SiteConfig cache (it caches the decrypted map) ==="
mysql -uroot -p"$(grep ^DB_PASSWORD /var/www/html/mathapi/.env | cut -d= -f2-)" vocab -e "DELETE FROM cache WHERE \`key\` LIKE 'site_config:%';" 2>/dev/null
php artisan config:cache 2>&1 | tail -1
systemctl reload apache2

echo ""
echo "=== Confirm runtime mail config ==="
php artisan tinker --execute='echo "host=".config("mail.mailers.smtp.host"), PHP_EOL, "user=".config("mail.mailers.smtp.username"), PHP_EOL, "pass_len=".strlen((string)config("mail.mailers.smtp.password")) . PHP_EOL;' 2>&1

echo ""
echo "=== NOTE: privateemail likely still in temporary lockout (454)."
echo "    Wait ~10 minutes before testing again. To test now via direct SMTP:"
echo "    php artisan tinker --execute='try { Mail::raw(\"vocab test\",function(\$m){\$m->to(\"pamelaliusm@gmail.com\")->subject(\"vocab test\");}); echo \"SENT\\n\"; } catch(\\Throwable \$e) { echo \"FAIL: \".\$e->getMessage().\"\\n\"; }'"
