#!/bin/bash
set -euo pipefail

# scripts/lab/start_infra.sh

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}🚀 Starting Lab Infrastructure (Postgres, Redis, RabbitMQ)...${NC}"

if ! command -v docker &> /dev/null; then
    echo "❌ Docker could not be found. Please install Docker."
    exit 1
fi

# Launch Docker Compose in detached mode
docker compose -f infra/docker-compose.lab.yml up -d

echo -e "${YELLOW}⏳ Waiting for services to be healthy...${NC}"

# Simple wait loop for Postgres
TIMEOUT=60
COUNT=0
until docker exec veza-lab-postgres pg_isready -U veza -d veza_lab > /dev/null 2>&1; do
    sleep 1
    COUNT=$((COUNT+1))
    if [ $COUNT -ge $TIMEOUT ]; then
        echo "❌ Timed out waiting for Postgres to be ready."
        exit 1
    fi
    echo -n "."
done
echo ""

echo -e "${GREEN}✅ Infrastructure is UP!${NC}"
echo "---------------------------------------------------"
# Create separate databases for services to avoid migration collisions (sqlx)
echo -e "${YELLOW}🛠️  Creating separate databases (veza_chat, veza_stream)...${NC}"
docker exec veza-lab-postgres psql -U veza -d veza_lab -c "CREATE DATABASE veza_chat;" || true
docker exec veza-lab-postgres psql -U veza -d veza_lab -c "CREATE DATABASE veza_stream;" || true

# Install required extensions in veza_chat
echo -e "${YELLOW}🔌 Installing extensions in veza_chat...${NC}"
docker exec veza-lab-postgres psql -U veza -d veza_chat -c 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; CREATE EXTENSION IF NOT EXISTS "pgcrypto"; CREATE EXTENSION IF NOT EXISTS "btree_gin"; CREATE EXTENSION IF NOT EXISTS "pg_trgm";' || true

docker compose -f infra/docker-compose.lab.yml ps
echo "---------------------------------------------------"
echo "Use the following DSN for your applications:"
echo "VEZA_LAB_DSN='postgres://veza:veza_password@localhost:5432/veza_lab?sslmode=disable'"
