#!/bin/bash

# ============================================
# 发票服务部署脚本
# ============================================

set -e

# 配置
SERVICE_NAME="invoice-service"
SERVICE_PORT=8086
IMAGE_NAME="erp/invoice-service"
IMAGE_TAG="${1:-latest}"
NAMESPACE="erp"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

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

# 检查Docker
check_docker() {
    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装，请先安装Docker"
        exit 1
    fi
    log_info "Docker已安装"
}

# 构建镜像
build_image() {
    log_info "开始构建Docker镜像: ${IMAGE_NAME}:${IMAGE_TAG}"
    
    cd "$(dirname "$0")/.."
    
    docker build -t ${IMAGE_NAME}:${IMAGE_TAG} .
    docker tag ${IMAGE_NAME}:${IMAGE_TAG} ${IMAGE_NAME}:latest
    
    log_info "镜像构建完成"
}

# 推送镜像
push_image() {
    log_info "推送镜像到仓库"
    
    # 如果使用私有仓库，需要先登录
    # docker login registry.example.com
    
    docker push ${IMAGE_NAME}:${IMAGE_TAG}
    docker push ${IMAGE_NAME}:latest
    
    log_info "镜像推送完成"
}

# Docker Compose部署
deploy_docker_compose() {
    log_info "使用Docker Compose部署服务"
    
    cd "$(dirname "$0")/.."
    
    docker-compose down || true
    docker-compose up -d
    
    log_info "服务部署完成，端口: ${SERVICE_PORT}"
}

# Kubernetes部署
deploy_kubernetes() {
    log_info "使用Kubernetes部署服务"
    
    kubectl apply -f deploy/k8s/deployment.yaml -n ${NAMESPACE}
    
    log_info "Kubernetes部署完成"
}

# 等待服务启动
wait_for_service() {
    log_info "等待服务启动..."
    
    max_attempts=30
    attempt=0
    
    while [ $attempt -lt $max_attempts ]; do
        if curl -sf http://localhost:${SERVICE_PORT}/actuator/health > /dev/null 2>&1; then
            log_info "服务已就绪"
            return 0
        fi
        
        attempt=$((attempt + 1))
        log_info "等待服务启动... ($attempt/$max_attempts)"
        sleep 2
    done
    
    log_error "服务启动超时"
    return 1
}

# 执行数据库迁移
run_migrations() {
    log_info "执行数据库迁移..."
    
    # 执行SQL迁移脚本
    mysql -h 111.229.80.149 -u root -pnihao588+ erp_db < src/main/resources/db/migration/V1__create_invoices_table.sql
    
    log_info "数据库迁移完成"
}

# 查看日志
view_logs() {
    docker-compose logs -f ${SERVICE_NAME}
}

# 回滚
rollback() {
    log_warn "开始回滚服务..."
    
    docker pull ${IMAGE_NAME}:previous
    docker-compose down
    docker-compose up -d
    
    log_info "回滚完成"
}

# 显示帮助
show_help() {
    echo "用法: $0 [命令] [标签]"
    
    echo ""
    echo "命令:"
    echo "  build              构建Docker镜像"
    echo "  push               推送镜像到仓库"
    echo "  deploy             部署服务 (Docker Compose)"
    echo "  deploy-k8s         部署服务 (Kubernetes)"
    echo "  migrate            执行数据库迁移"
    echo "  logs               查看服务日志"
    echo "  rollback           回滚到上一版本"
    echo "  help               显示帮助"
    
    echo ""
    echo "示例:"
    echo "  $0 build v1.0.0           # 构建v1.0.0版本镜像"
    echo "  $0 deploy v1.0.0          # 部署v1.0.0版本"
    echo "  $0 deploy-k8s             # 使用Kubernetes部署"
}

# 主函数
main() {
    COMMAND="${1:-help}"
    shift || true
    
    case ${COMMAND} in
        build)
            check_docker
            build_image
            ;;
        push)
            check_docker
            push_image
            ;;
        deploy)
            check_docker
            deploy_docker_compose
            wait_for_service
            ;;
        deploy-k8s)
            deploy_kubernetes
            ;;
        migrate)
            run_migrations
            ;;
        logs)
            view_logs
            ;;
        rollback)
            rollback
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            log_error "未知命令: ${COMMAND}"
            show_help
            exit 1
            ;;
    esac
}

main "$@"
