#!/bin/bash
set -e

echo "🚀 Preparing deployment via Git..."

# Ensure we start with SQLite for local build
sed -i '' 's/provider = "mysql"/provider = "sqlite"/g' prisma/schema.prisma || true

echo "Building Next.js app locally with SQLite to collect page data..."
npx prisma generate
npm run build

# Swap to MySQL schema for deployment
echo "Swapping to MySQL schema for production..."
sed -i '' 's/provider = "sqlite"/provider = "mysql"/g' prisma/schema.prisma
# We don't need to generate Prisma client here. The postinstall script on cPanel handles it.

echo "Committing built files and production schema to Git..."
git add .
git commit -m "Deploy: Update build and push to cPanel" || true
git push origin main

echo "Reverting schema back to SQLite for local development..."
sed -i '' 's/provider = "mysql"/provider = "sqlite"/g' prisma/schema.prisma
# Re-generate the local client for SQLite
npx prisma generate

echo "✅ Git push complete!"
echo "------------------------------------------------------"
echo "ACTION REQUIRED:"
echo "1. Go to cPanel -> Git Version Control"
echo "2. Click 'Update from Remote'"
echo "3. Click 'Deploy HEAD Commit'"
echo "4. (Optional) Run 'npm install' in cPanel terminal to update packages."
echo "------------------------------------------------------"

echo "Waiting for you to trigger deployment in cPanel... (Sleeping for 20 seconds)"
# Give the user time to click the buttons before we try to migrate
sleep 20

echo "Triggering database migration..."
curl -s "https://daily-app.eligence.dev/api/migrate?token=deploy123"

echo ""
echo "🚀 Rollout complete!"
