pipeline {
    agent any

    environment {
        NODE_VERSION = '20'
        PROJECT_DIR = 'everything-is-suitable-uniapp'
    }

    stages {
        stage('Install Dependencies') {
            steps {
                dir(env.PROJECT_DIR) {
                    sh 'npm ci'
                }
            }
        }

        stage('Lint') {
            steps {
                dir(env.PROJECT_DIR) {
                    sh 'npx eslint src/ --ext .ts,.vue --max-warnings 0 || true'
                }
            }
        }

        stage('Unit Tests') {
            steps {
                dir(env.PROJECT_DIR) {
                    sh 'npm run test:coverage'
                }
            }
            post {
                always {
                    dir(env.PROJECT_DIR) {
                        junit allowEmptyResults: true, testResults: 'coverage/junit.xml'
                        publishHTML(target: [
                            reportDir: 'coverage',
                            reportFiles: 'index.html',
                            reportName: 'Coverage Report'
                        ])
                    }
                }
            }
        }

        stage('Build H5') {
            steps {
                dir(env.PROJECT_DIR) {
                    sh 'npm run build:h5'
                }
            }
        }

        stage('Build WeChat Mini Program') {
            when {
                branch 'main'
            }
            steps {
                dir(env.PROJECT_DIR) {
                    sh 'npm run build:mp-weixin'
                }
            }
        }

        stage('E2E Tests') {
            steps {
                dir(env.PROJECT_DIR) {
                    sh 'npx playwright install --with-deps chromium'
                    sh 'npm run test:e2e || true'
                }
            }
            post {
                always {
                    dir(env.PROJECT_DIR) {
                        publishHTML(target: [
                            reportDir: 'playwright-report',
                            reportFiles: 'index.html',
                            reportName: 'E2E Report'
                        ])
                    }
                }
            }
        }
    }

    post {
        always {
            dir(env.PROJECT_DIR) {
                cleanWs()
            }
        }
        success {
            echo 'Pipeline completed successfully'
        }
        failure {
            echo 'Pipeline failed - check stage logs for details'
        }
    }
}
