#!/usr/bin/env bash
set -e
DBPASS=$(grep ^DB_PASSWORD /var/www/html/mathapi/.env | cut -d= -f2-)

echo "=== Verifying dump file ==="
ls -lh /tmp/vocab-data.sql.gz
echo ""

echo "=== Decompressing + importing into vocab DB ==="
gunzip -c /tmp/vocab-data.sql.gz | mysql -uroot -p"$DBPASS" --default-character-set=utf8mb4 vocab 2>&1 | head -30

echo ""
echo "=== Row counts after import ==="
mysql -uroot -p"$DBPASS" vocab -Nse "
  SELECT TABLE_NAME, TABLE_ROWS
  FROM information_schema.tables
  WHERE table_schema='vocab'
  ORDER BY TABLE_ROWS DESC
  LIMIT 30;
" 2>/dev/null
echo ""

echo "=== Sanity check ==="
mysql -uroot -p"$DBPASS" vocab -Nse "SELECT COUNT(*) FROM users;" 2>/dev/null  | awk '{print "users:        " $1}'
mysql -uroot -p"$DBPASS" vocab -Nse "SELECT COUNT(*) FROM schools;" 2>/dev/null | awk '{print "schools:      " $1}'
mysql -uroot -p"$DBPASS" vocab -Nse "SELECT COUNT(*) FROM words;" 2>/dev/null   | awk '{print "words:        " $1}'
mysql -uroot -p"$DBPASS" vocab -Nse "SELECT COUNT(*) FROM questions;" 2>/dev/null | awk '{print "questions:    " $1}'
mysql -uroot -p"$DBPASS" vocab -Nse "SELECT COUNT(*) FROM test_types;" 2>/dev/null | awk '{print "test_types:   " $1}'
mysql -uroot -p"$DBPASS" vocab -Nse "SELECT email, is_premium, is_unlimited_lives FROM users LIMIT 5;" 2>/dev/null

echo ""
echo "=== Clearing stale cache entries (site_config will be rebuilt at runtime) ==="
mysql -uroot -p"$DBPASS" vocab -Nse "TRUNCATE cache;" 2>/dev/null
echo "cache cleared"

echo ""
echo "=== Re-encrypting secret configs with this server's APP_KEY ==="
# Encrypted Config rows were written with the SOURCE machine's APP_KEY. After
# importing, the local Crypt::decryptString fails on them, which silently
# turns mail passwords / API keys into garbage downstream. Run through every
# `password`/`secret` row, decrypt with the OLD key if we can (usually we
# can't — different env), else prompt the operator to re-set via Filament.
#
# In practice the simplest fix is: re-set mail_password via the admin UI
# OR via tinker `$c = Config::where('key','mail_password')->first(); $c->value = '<plain>'; $c->save();`
# The mutator on Config.php picks up the new APP_KEY.
cd /var/www/html/vocabapi
php artisan tinker --execute='$rows=\App\Models\Config::whereIn("type",["password","secret"])->get(); foreach($rows as $c){ $stored=$c->getRawOriginal("value"); if(!$stored){ continue; } try{ \Illuminate\Support\Facades\Crypt::decryptString($stored); echo "  OK: {$c->key}".PHP_EOL; }catch(\Throwable $e){ echo "  NEEDS RESET: {$c->key} (id={$c->id}) — re-enter via admin or tinker".PHP_EOL; } }' 2>&1 | grep -E "OK:|NEEDS RESET:"
