pipeline {
  agent any

  parameters {
    string(name: 'IMAGE_TAG', defaultValue: 'latest', description: '镜像 Tag')
    booleanParam(name: 'DEPLOY', defaultValue: true, description: '构建后是否自动部署')
  }

  environment {
    ACR_REGISTRY  = 'crpi-n44qjpuucgjt8e8c.cn-beijing.personal.cr.aliyuncs.com'
    ACR_NAMESPACE = 'xuqmgroup'
    ACR_USERNAME  = 'xuqinmin12'
    PROD_HOST     = '106.54.23.149'
    PROD_USER     = 'ubuntu'
    COMPOSE_FILE  = '/opt/xuqm/deploy/compose.production.yaml'
    IMAGE_NAME    = 'web'
  }

  stages {
    stage('Checkout') {
      steps { checkout scm }
    }

    stage('Docker Build & Push') {
      steps {
        withCredentials([string(credentialsId: 'ACR_PASSWORD', variable: 'ACR_PASS')]) {
          script {
            def fullImage = "${ACR_REGISTRY}/${ACR_NAMESPACE}/${IMAGE_NAME}:${params.IMAGE_TAG}"
            sh """
              docker login ${ACR_REGISTRY} -u ${ACR_USERNAME} -p \${ACR_PASS}
              docker build -t ${fullImage} .
              docker push ${fullImage}
              docker rmi ${fullImage}
            """
          }
        }
      }
    }

    stage('Deploy to Production') {
      when { expression { return params.DEPLOY } }
      steps {
        withCredentials([sshUserPrivateKey(credentialsId: 'PROD_SSH_KEY', keyFileVariable: 'SSH_KEY')]) {
          script {
            def fullImage = "${ACR_REGISTRY}/${ACR_NAMESPACE}/${IMAGE_NAME}:${params.IMAGE_TAG}"
            sh """
              ssh -i \${SSH_KEY} -o StrictHostKeyChecking=no ${PROD_USER}@${PROD_HOST} \
                "docker pull ${fullImage} && \
                 docker compose -f ${COMPOSE_FILE} up -d --no-deps web && \
                 docker image prune -f"
            """
          }
        }
      }
    }
  }

  post {
    success { echo "✅ web:${params.IMAGE_TAG} 构建部署成功" }
    failure  { echo "❌ 构建失败，请检查日志" }
  }
}
