#!/bin/bash
set -euo pipefail

# scripts/lab/apply_all_migrations.sh

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# Default DSN if not set
export VEZA_LAB_DSN="${VEZA_LAB_DSN:-postgres://veza:veza_password@localhost:5432/veza_lab?sslmode=disable}"

echo -e "${GREEN}🔄 orchestrating migrations for all services...${NC}"
echo -e "DSN: $VEZA_LAB_DSN"

# 1. veza-backend-api
echo -e "\n${YELLOW}>>> veza-backend-api : applying migrations...${NC}"
(
    cd veza-backend-api || exit 1
    export DATABASE_URL="$VEZA_LAB_DSN"
    
    if [ -x scripts/apply_migrations_lab.sh ]; then
        ./scripts/apply_migrations_lab.sh
    else
        # Fallback to Go standard migration if script missing
        echo "Using go run cmd/migrate_tool/main.go"
        go run cmd/migrate_tool/main.go
    fi
) || { echo -e "${RED}❌ veza-backend-api migrations failed${NC}"; exit 1; }

# 2. veza-stream-server
echo -e "\n${YELLOW}>>> veza-stream-server : applying migrations...${NC}"
(
    cd veza-stream-server || exit 1
    # Stream server needs access to core tables (tracks), so use standard VEZA_LAB_DSN
    export DATABASE_URL="$VEZA_LAB_DSN"
    
    # Try using sqlx directly first as it is more robust for orchestrators
    if command -v sqlx &> /dev/null; then
        echo "Using sqlx migrate run"
        sqlx migrate run --database-url "$DATABASE_URL"
    elif [ -x scripts/apply_migrations_lab.sh ]; then
        echo "Using scripts/apply_migrations_lab.sh"
        ./scripts/apply_migrations_lab.sh
    else
        echo -e "${RED}❌ No migration mechanism found for stream-server (install sqlx-cli)${NC}"
        exit 1
    fi
) || { echo -e "${RED}❌ veza-stream-server migrations failed${NC}"; exit 1; }

# 3. veza-chat-server
echo -e "\n${YELLOW}>>> veza-chat-server : applying migrations...${NC}"
(
    cd veza-chat-server || exit 1
    # Use veza_chat DB
    export DATABASE_URL="${VEZA_LAB_DSN/veza_lab/veza_chat}"
    echo "DB: $DATABASE_URL"
    # Some services might use CHAT_DATABASE_URL
    export CHAT_DATABASE_URL="$DATABASE_URL"
    export VEZA_LAB_DSN="$DATABASE_URL" # Check if internal script uses this
    
    if command -v sqlx &> /dev/null; then
        echo "Using sqlx migrate run"
        # Check if migrations dir exists
        if [ -d "migrations" ]; then
            sqlx migrate run --database-url "$DATABASE_URL"
        else
             echo -e "${YELLOW}⚠️  No migrations directory found in veza-chat-server, skipping...${NC}"
        fi
    elif [ -x scripts/apply_migrations_lab.sh ]; then
        ./scripts/apply_migrations_lab.sh
    else
        echo -e "${YELLOW}⚠️  No migration mechanism found for chat-server, skipping...${NC}"
    fi
) || { echo -e "${RED}❌ veza-chat-server migrations failed${NC}"; exit 1; }

echo -e "\n${GREEN}✅ All migrations applied successfully!${NC}"
