#!/bin/bash

# Production Deployment Script for Women's Safety Backend
# Usage: ./deploy-production.sh [version]

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
VERSION=${1:-latest}
COMPOSE_FILE="docker-compose.prod.yml"
ENV_FILE=".env.prod"

echo -e "${BLUE}🚀 Starting Women's Safety Backend Deployment${NC}"
echo -e "${BLUE}Version: ${VERSION}${NC}"
echo -e "${BLUE}Environment: Production${NC}"
echo

# Check if environment file exists
if [ ! -f "$ENV_FILE" ]; then
    echo -e "${RED}❌ Environment file $ENV_FILE not found!${NC}"
    echo -e "${YELLOW}💡 Copy .env.prod.example to .env.prod and configure it${NC}"
    exit 1
fi

# Load environment variables
source "$ENV_FILE"
export TAG="$VERSION"

echo -e "${YELLOW}🔍 Pre-deployment checks...${NC}"

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
    echo -e "${RED}❌ Docker is not running!${NC}"
    exit 1
fi

# Check if required images exist
echo -e "${YELLOW}📦 Checking Docker images...${NC}"
SERVICES=("user-service" "emergency-service" "location-service" "calendar-service" "notification-service" "api-gateway")

for service in "${SERVICES[@]}"; do
    if ! docker image inspect "women-safety/$service:$VERSION" > /dev/null 2>&1; then
        echo -e "${YELLOW}⬇️ Pulling women-safety/$service:$VERSION...${NC}"
        docker pull "women-safety/$service:$VERSION" || {
            echo -e "${RED}❌ Failed to pull women-safety/$service:$VERSION${NC}"
            exit 1
        }
    else
        echo -e "${GREEN}✅ women-safety/$service:$VERSION exists${NC}"
    fi
done

# Database backup before deployment
echo -e "${YELLOW}💾 Creating database backup...${NC}"
BACKUP_FILE="backup-$(date +%Y%m%d-%H%M%S).sql"
docker-compose -f "$COMPOSE_FILE" exec -T postgres-primary pg_dump -U postgres women_safety_prod > "$BACKUP_FILE" || {
    echo -e "${YELLOW}⚠️ Backup failed or database not running${NC}"
}

# Health check function
health_check() {
    local service_url=$1
    local service_name=$2
    local max_attempts=30
    local attempt=1
    
    echo -e "${YELLOW}🏥 Health checking $service_name...${NC}"
    
    while [ $attempt -le $max_attempts ]; do
        if curl -s -f "$service_url/health" > /dev/null 2>&1; then
            echo -e "${GREEN}✅ $service_name is healthy${NC}"
            return 0
        fi
        
        echo -n "."
        sleep 2
        ((attempt++))
    done
    
    echo -e "${RED}❌ $service_name health check failed${NC}"
    return 1
}

# Deploy with zero downtime
echo -e "${YELLOW}🔄 Starting rolling deployment...${NC}"

# Start new services
docker-compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" up -d

# Wait for services to be ready
sleep 10

# Health checks
echo -e "${YELLOW}🏥 Running health checks...${NC}"
health_check "http://localhost:8000" "API Gateway"
health_check "http://localhost:8001" "User Service"
health_check "http://localhost:8002" "Emergency Service"
health_check "http://localhost:8003" "Location Service"
health_check "http://localhost:8004" "Calendar Service"
health_check "http://localhost:8005" "Notification Service"

# Smoke tests
echo -e "${YELLOW}🧪 Running smoke tests...${NC}"

# Test user registration
SMOKE_EMAIL="smoke-test-$(date +%s)@example.com"
REGISTRATION_RESPONSE=$(curl -s -X POST "http://localhost:8000/api/v1/register" \
    -H "Content-Type: application/json" \
    -d "{\"email\":\"$SMOKE_EMAIL\",\"password\":\"smoketest123\",\"first_name\":\"Smoke\",\"last_name\":\"Test\",\"phone\":\"+1234567890\"}" \
    -w "%{http_code}")

if [[ $REGISTRATION_RESPONSE == *"201"* ]]; then
    echo -e "${GREEN}✅ User registration smoke test passed${NC}"
else
    echo -e "${RED}❌ User registration smoke test failed${NC}"
    echo -e "${YELLOW}Response: $REGISTRATION_RESPONSE${NC}"
fi

# Clean up old images
echo -e "${YELLOW}🧹 Cleaning up old Docker images...${NC}"
docker image prune -f

# Final status
echo
echo -e "${GREEN}🎉 Deployment completed successfully!${NC}"
echo -e "${GREEN}📊 Services Status:${NC}"
docker-compose -f "$COMPOSE_FILE" ps

echo
echo -e "${BLUE}🔗 Access URLs:${NC}"
echo -e "${BLUE}   API Gateway: https://$DOMAIN${NC}"
echo -e "${BLUE}   Monitoring: http://$DOMAIN:3000${NC}"
echo -e "${BLUE}   Metrics: http://$DOMAIN:9090${NC}"
echo

echo -e "${GREEN}✅ Women's Safety Backend v$VERSION deployed successfully!${NC}"

# Send deployment notification (if webhook configured)
if [ ! -z "$SLACK_WEBHOOK" ]; then
    curl -X POST -H 'Content-type: application/json' \
        --data "{\"text\":\"🚀 Women's Safety Backend v$VERSION deployed successfully to production!\"}" \
        "$SLACK_WEBHOOK" > /dev/null 2>&1 || true
fi