#!/bin/bash
set -e

SERVICE_NAME="sku-match-service"
SERVICE_DIR="/root/.openclaw/workspace/erp-java-backend/services/sku-match-service"
IMAGE_NAME="erp/${SERVICE_NAME}:latest"
CONTAINER_NAME="${SERVICE_NAME}"

echo "========== ${SERVICE_NAME} 部署开始 =========="

cd ${SERVICE_DIR}

# 1. 初始化数据库
echo "[1/4] 初始化数据库..."
mysql -h 111.229.80.149 -u root -pnihao588+ erp_db < sql/init.sql 2>/dev/null || echo "数据库已存在，跳过初始化"

# 2. 构建镜像
echo "[2/4] 构建Docker镜像..."
docker build -t ${IMAGE_NAME} .

# 3. 停止并删除旧容器
echo "[3/4] 停止旧容器..."
docker stop ${CONTAINER_NAME} 2>/dev/null || true
docker rm ${CONTAINER_NAME} 2>/dev/null || true

# 4. 启动新容器
echo "[4/4] 启动新容器..."
docker run -d \
    --name ${CONTAINER_NAME} \
    --restart always \
    -p 8084:8084 \
    -e SPRING_PROFILES_ACTIVE=prod \
    -e SPRING_DATASOURCE_URL="jdbc:mysql://111.229.80.149:3306/erp_db?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false" \
    -e SPRING_DATASOURCE_USERNAME=root \
    -e SPRING_DATASOURCE_PASSWORD=nihao588+ \
    -e SPRING_DATA_REDIS_HOST=111.229.80.149 \
    -e SPRING_DATA_REDIS_PORT=6379 \
    -e SPRING_DATA_REDIS_PASSWORD="Y(@r5tGk9\$Lp2" \
    -e SPRING_CLOUD_NACOS_DISCOVERY_SERVER_ADDR=111.229.80.149:8848 \
    -e SPRING_CLOUD_NACOS_CONFIG_SERVER_ADDR=111.229.80.149:8848 \
    ${IMAGE_NAME}

echo "等待服务启动..."
sleep 10

# 健康检查
for i in {1..10}; do
    if curl -sf http://localhost:8084/actuator/health > /dev/null 2>&1; then
        echo "✅ ${SERVICE_NAME} 部署成功！"
        exit 0
    fi
    echo "等待服务就绪... ($i/10)"
    sleep 3
done

echo "❌ ${SERVICE_NAME} 部署失败，请检查日志"
docker logs ${CONTAINER_NAME}
exit 1
