#!/bin/bash

# Phosphat Report Deployment Script
# This script helps deploy the application using Docker Compose

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if .env file exists
if [ ! -f .env ]; then
    print_warning ".env file not found. Creating from .env.production template..."
    cp .env.production .env
    print_warning "Please edit .env file with your production values before continuing!"
    exit 1
fi

# Create necessary directories
print_status "Creating necessary directories..."
mkdir -p data backups logs

# Set proper permissions
print_status "Setting directory permissions..."
chmod 755 data backups logs

# Check if Docker and Docker Compose are installed
if ! command -v docker &> /dev/null; then
    print_error "Docker is not installed. Please install Docker first."
    exit 1
fi

if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
    print_error "Docker Compose is not installed. Please install Docker Compose first."
    exit 1
fi

# Function to deploy
deploy() {
    print_status "Starting deployment..."
    
    # Pull latest images (if using external registry)
    # docker-compose pull
    
    # Build and start services
    print_status "Building and starting services..."
    docker-compose up -d --build
    
    # Wait for services to be healthy
    print_status "Waiting for services to be healthy..."
    sleep 10
    
    # Check if application is running
    if docker-compose ps | grep -q "Up"; then
        print_success "Application deployed successfully!"
        print_status "Application is running at: http://localhost:${APP_PORT:-3000}"
        
        # Show logs
        print_status "Recent logs:"
        docker-compose logs --tail=20 app
    else
        print_error "Deployment failed. Check logs:"
        docker-compose logs app
        exit 1
    fi
}

# Function to stop services
stop() {
    print_status "Stopping services..."
    docker-compose down
    print_success "Services stopped."
}

# Function to restart services
restart() {
    print_status "Restarting services..."
    docker-compose restart
    print_success "Services restarted."
}

# Function to show logs
logs() {
    docker-compose logs -f app
}

# Function to backup database
backup() {
    print_status "Creating database backup..."
    timestamp=$(date +%Y%m%d_%H%M%S)
    docker-compose exec app cp /app/data/production.db /app/data/backup_${timestamp}.db
    print_success "Backup created: backup_${timestamp}.db"
}

# Function to show status
status() {
    print_status "Service status:"
    docker-compose ps
    
    print_status "Health check:"
    curl -s http://localhost:${APP_PORT:-3000}/health | jq . || echo "Health check failed or jq not installed"
}

# Main script logic
case "${1:-deploy}" in
    deploy)
        deploy
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    logs)
        logs
        ;;
    backup)
        backup
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {deploy|stop|restart|logs|backup|status}"
        echo ""
        echo "Commands:"
        echo "  deploy  - Build and deploy the application (default)"
        echo "  stop    - Stop all services"
        echo "  restart - Restart all services"
        echo "  logs    - Show application logs"
        echo "  backup  - Create database backup"
        echo "  status  - Show service status and health"
        exit 1
        ;;
esac