pipeline {
    agent none  // 全局不指定，局部单独声明
    environment {
        IMAGE_NAME = 'lpt-fe:0.0'
        CONTAINER_NAME = 'LPT_FE'
        HOST_PORT = '5158'
        CONTAINER_PORT = '80'
    }
    stages {
        stage('Install Dependencies') {
            agent {
                docker {
                    image 'node:20-alpine'
                    args '-v ${WORKSPACE}/.npm:/.npm -v ${WORKSPACE}/node_modules:/app/node_modules'
                }
            }
            steps {
                sh '''
                  npm config set cache /.npm
                  npm install
                '''
            }
        }

        stage('Type Check & Build') {
            agent {
                docker {
                    image 'node:20-alpine'
                    args '-v ${WORKSPACE}/.npm:/.npm -v ${WORKSPACE}/node_modules:/app/node_modules'
                }
            }
            steps {
                sh '''
                  npm run type-check
                  npm run build
                '''
            }
        }

        stage('Build Docker Image') {
            agent any  // Jenkins默认节点，有Docker命令
            steps {
                sh '''
                  docker build -t $IMAGE_NAME .
                '''
            }
        }

        stage('Run Docker Container') {
            agent any
            steps {
                sh '''
                  docker rm -f $CONTAINER_NAME || true
                  docker run -d --name $CONTAINER_NAME \\
                    -p $HOST_PORT:$CONTAINER_PORT \\
                    $IMAGE_NAME
                '''
            }
        }

        stage('Run Docker Container') {
            agent any
            steps {
                        sh '''
                  docker rm -f $CONTAINER_NAME || true
                  docker run -d --name $CONTAINER_NAME \\
                    -p $HOST_PORT:$CONTAINER_PORT \\
                    --health-cmd="curl -f http://localhost:$CONTAINER_PORT || exit 1" \\
                    --health-interval=10s \\
                    --health-timeout=5s \\
                    --health-retries=3 \\
                    $IMAGE_NAME
                '''
            }
        }

    }
}
