#!/bin/bash
# CRM Clinicas — Production Deployment Script
# Usage: ./scripts/deploy.sh

set -euo pipefail

echo "=== CRM Clinicas — Deploy ==="

# 1. Build Next.js Docker image
echo "[1/4] Building Next.js Docker image..."
docker build -t crm-clinicas-app:latest -f Dockerfile .

# 2. Ensure Supabase is running
echo "[2/4] Checking Supabase stack..."
cd docker
docker compose --env-file .env.supabase up -d
cd ..

# 3. Run migrations
echo "[3/4] Running database migrations..."
for f in supabase/migrations/*.sql; do
  echo "  -> $f"
  cat "$f" | docker exec -i -e PGPASSWORD=CrmCl1n1c4s2026SecretPwd docker-db-1 psql -U supabase_admin -d postgres > /dev/null 2>&1 || true
done

# 4. Start/restart Next.js
echo "[4/4] Starting Next.js app..."
docker stop crm-app 2>/dev/null || true
docker rm crm-app 2>/dev/null || true
docker run -d \
  --name crm-app \
  --network docker_default \
  -p 3000:3000 \
  -e NEXT_PUBLIC_SUPABASE_URL=http://kong:8000 \
  -e NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0 \
  -e SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU \
  crm-clinicas-app:latest

echo ""
echo "=== Deploy complete ==="
echo "  App:     http://localhost:3000"
echo "  Studio:  http://localhost:3001"
echo "  API:     http://localhost:8000"
