pipeline {
    agent any

    environment {
        APP_NAME      = 'no-whatever'
        AMAP_KEY      = '7f6be40a6de3f7fbb7bc3f825b67573b'
        DEEPSEEK_KEY  = credentials('deepseek-api-key')
    }

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

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

        stage('Build Docker Image') {
            steps {
                sh "docker build --build-arg NEXT_PUBLIC_AMAP_API_KEY=${AMAP_KEY} -t ${APP_NAME}:${BUILD_NUMBER} -t ${APP_NAME}:latest ."
            }
        }

        stage('Deploy') {
            steps {
                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 3000:3000 \
                        -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"
        }
    }
}
