pipeline {
    agent any

    environment {
        APP_NAME = 'no-whatever'
    }

    triggers {
        GenericTrigger(tokenCredentialId: 'no-whatever-deploy-token')
    }

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

        stage('Node Runtime') {
            steps {
                script {
                    if (sh(returnStatus: true, script: 'command -v npm >/dev/null 2>&1') != 0) {
                        echo "System npm not found, trying Jenkins NodeJS tool 'node20'"
                        try {
                            def nodeHome = tool name: 'node20', type: 'jenkins.plugins.nodejs.tools.NodeJSInstallation'
                            env.PATH = "${nodeHome}/bin:${env.PATH}"
                        } catch (err) {
                            error "npm not found and Jenkins NodeJS tool 'node20' is unavailable. Please install NodeJS plugin and configure tool name 'node20'. Root cause: ${err}"
                        }
                    }
                }
                sh 'node -v'
                sh 'npm -v'
            }
        }

        stage('Install Dependencies') {
            steps {
                sh 'npm ci'
            }
        }

        stage('Quality Gate') {
            steps {
                sh 'npm run lint'
                sh 'npx tsc --noEmit'
                sh 'npm run test:coverage'
            }
        }

        stage('E2E Gate') {
            options {
                timeout(time: 20, unit: 'MINUTES')
            }
            steps {
                retry(2) {
                    sh 'npm run test:e2e:install'
                }
                sh 'npm run test:e2e'
            }
            post {
                always {
                    archiveArtifacts artifacts: 'playwright-report/**,test-results/**', allowEmptyArchive: true
                }
            }
        }

        stage('Build Docker Image') {
            steps {
                withCredentials([
                    string(credentialsId: 'amap-api-key', variable: 'AMAP_KEY')
                ]) {
                    sh "docker build --build-arg NEXT_PUBLIC_AMAP_API_KEY=${AMAP_KEY} -t ${APP_NAME}:${BUILD_NUMBER} -t ${APP_NAME}:latest ."
                }
            }
        }

        stage('Deploy') {
            steps {
                withCredentials([
                    string(credentialsId: 'amap-api-key', variable: 'AMAP_KEY'),
                    string(credentialsId: 'deepseek-api-key', variable: 'DEEPSEEK_KEY')
                ]) {
                    sh """
                        docker stop ${APP_NAME} || true
                        docker rm ${APP_NAME} || true
                        mkdir -p /data/${APP_NAME}
                        chown 1001:1001 /data/${APP_NAME}
                        docker run -d \
                            --name ${APP_NAME} \
                            --network nginx \
                            -p 3721:3721 \
                            -v /data/${APP_NAME}:/app/data \
                            -e DATABASE_URL=file:/app/data/prod.db \
                            -e AMAP_API_KEY=${AMAP_KEY} \
                            -e DEEPSEEK_API_KEY=${DEEPSEEK_KEY} \
                            --restart unless-stopped \
                            ${APP_NAME}:latest
                    """
                }
            }
        }
    }

    post {
        success {
            echo "Deployed ${APP_NAME} build #${BUILD_NUMBER} successfully"
        }
        failure {
            echo "Build #${BUILD_NUMBER} failed"
        }
    }
}
