#!/bin/bash
set -e

echo "=== GENERATING SQLX QUERY CACHE ==="
echo ""

# Install sqlx-cli if not present
if ! command -v cargo-sqlx &> /dev/null; then
    echo "Installing sqlx-cli..."
    cargo install sqlx-cli --no-default-features --features postgres
fi

# Set DATABASE_URL to local postgres container
export DATABASE_URL="postgres://corrosion:${DB_PASSWORD:-corrosion_dev}@localhost:5432/corrosion"

echo "Testing database connection..."
if ! psql "$DATABASE_URL" -c "SELECT 1" > /dev/null 2>&1; then
    echo "❌ Cannot connect to database. Make sure PostgreSQL container is running."
    echo "   Run: docker ps | grep corrosion-db"
    exit 1
fi

echo "✅ Database connection successful"
echo ""

cd ~/corrosion-admin-panel/backend

echo "Generating sqlx query cache..."
cargo sqlx prepare --workspace

echo ""
echo "✅ Query cache generated in .sqlx/ directory"
echo ""
echo "Now commit and push the cache:"
echo "  git add .sqlx/"
echo "  git commit -m 'chore: Add sqlx offline query cache'"
echo "  git push"
echo ""
