#!/bin/bash
# =============================================================================
# TRADING PLATFORM - Deploy Script
# =============================================================================
# Uso: ./scripts/deploy.sh [build|push|deploy|full|rollback] [staging|prod]
# =============================================================================

set -e

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

# Configuration
PROJECT_NAME="trading-platform"
DOCKER_REGISTRY="${DOCKER_REGISTRY:-72.60.226.4:5000}"
DEPLOY_SERVER="${DEPLOY_SERVER:-72.60.226.4}"
DEPLOY_USER="${DEPLOY_USER:-deploy}"
DEPLOY_PATH="/opt/apps/${PROJECT_NAME}"
VERSION="${VERSION:-$(date +%Y%m%d%H%M%S)}"

# Functions
log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

check_prerequisites() {
    log_info "Verificando prerequisitos..."
    command -v docker >/dev/null 2>&1 || log_error "Docker no instalado"
    command -v ssh >/dev/null 2>&1 || log_error "SSH no disponible"
}

build_images() {
    log_info "Building Docker images (version: ${VERSION})..."

    # Backend
    log_info "Building backend..."
    docker build -t ${DOCKER_REGISTRY}/${PROJECT_NAME}-backend:${VERSION} \
        -f apps/backend/Dockerfile apps/backend/

    # Frontend
    log_info "Building frontend..."
    docker build -t ${DOCKER_REGISTRY}/${PROJECT_NAME}-frontend:${VERSION} \
        -f apps/frontend/Dockerfile apps/frontend/

    log_info "Build completado!"
}

push_images() {
    log_info "Pushing images to registry..."

    for service in backend frontend; do
        docker push ${DOCKER_REGISTRY}/${PROJECT_NAME}-${service}:${VERSION}
        docker tag ${DOCKER_REGISTRY}/${PROJECT_NAME}-${service}:${VERSION} \
            ${DOCKER_REGISTRY}/${PROJECT_NAME}-${service}:latest
        docker push ${DOCKER_REGISTRY}/${PROJECT_NAME}-${service}:latest
    done

    log_info "Push completado!"
}

deploy() {
    local env=${1:-prod}
    log_info "Deploying to ${env}..."

    ssh -o StrictHostKeyChecking=no ${DEPLOY_USER}@${DEPLOY_SERVER} << EOF
        set -e
        cd ${DEPLOY_PATH}

        echo "📦 Pulling images..."
        docker-compose -f docker/docker-compose.${env}.yml pull

        echo "🔄 Stopping containers..."
        docker-compose -f docker/docker-compose.${env}.yml down --remove-orphans

        echo "🚀 Starting containers..."
        docker-compose -f docker/docker-compose.${env}.yml up -d

        echo "🧹 Cleanup..."
        docker system prune -f

        echo "⏳ Waiting for health check..."
        sleep 15

        echo "✅ Deploy completado!"
EOF
}

rollback() {
    local env=${1:-prod}
    log_warn "Rolling back to previous version..."

    ssh -o StrictHostKeyChecking=no ${DEPLOY_USER}@${DEPLOY_SERVER} << EOF
        cd ${DEPLOY_PATH}
        docker-compose -f docker/docker-compose.${env}.yml down
        docker-compose -f docker/docker-compose.${env}.yml up -d --no-deps
EOF
}

health_check() {
    log_info "Running health check..."
    local url="https://api.trading.isem.dev/health"

    for i in {1..5}; do
        if curl -sf ${url} > /dev/null; then
            log_info "Health check passed!"
            return 0
        fi
        log_warn "Attempt ${i}/5 failed, retrying in 10s..."
        sleep 10
    done

    log_error "Health check failed!"
}

# Main
main() {
    local action=${1:-help}
    local env=${2:-prod}

    check_prerequisites

    case "$action" in
        build)
            build_images
            ;;
        push)
            push_images
            ;;
        deploy)
            deploy $env
            health_check
            ;;
        full)
            build_images
            push_images
            deploy $env
            health_check
            ;;
        rollback)
            rollback $env
            ;;
        *)
            echo "Uso: $0 {build|push|deploy|full|rollback} [staging|prod]"
            echo ""
            echo "Comandos:"
            echo "  build    - Construir imagenes Docker"
            echo "  push     - Subir imagenes al registry"
            echo "  deploy   - Desplegar en servidor"
            echo "  full     - Build + Push + Deploy"
            echo "  rollback - Revertir al despliegue anterior"
            exit 1
            ;;
    esac
}

main "$@"
