pipeline {
    agent {
        docker {
            image 'node:22-alpine'
            // Mount the host Docker socket so docker compose works inside the container
            args '-u root -v /var/run/docker.sock:/var/run/docker.sock'
        }
    }

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

        stage('Install') {
            steps {
                withCredentials([string(credentialsId: 'gitea-pat', variable: 'GITEA_PAT')]) {
                    sh '''
                        apk add --no-cache docker-cli docker-cli-compose
                        npm config set @davinti:registry https://git.davinti.com.br/api/packages/davinTI/npm/
                        npm config set //git.davinti.com.br/api/packages/davinTI/npm/:_authToken ${GITEA_PAT}
                        npm ci
                    '''
                }
            }
        }

        stage('Test') {
            steps {
                sh 'npm test -- --passWithNoTests'
            }
        }

        stage('E2E') {
            steps {
                withCredentials([
                    usernamePassword(credentialsId: 'gitea-docker-creds', usernameVariable: 'DOCKER_USER', passwordVariable: 'DOCKER_PASS')
                ]) {
                    sh '''
                        echo "$DOCKER_PASS" | docker login git.davinti.com.br -u "$DOCKER_USER" --password-stdin
                        docker compose -f tests/docker-compose.test.yml up -d
                        for i in $(seq 1 36); do
                            wget -q -O /dev/null http://localhost:18080/rest/public/test && break
                            echo "Aguardando Vitruvio... ($i/36)"
                            sleep 5
                        done
                        npm run test:e2e
                    '''
                }
            }
            post {
                always {
                    sh 'docker compose -f tests/docker-compose.test.yml down -v || true'
                }
            }
        }
    }

    post {
        always {
            cleanWs()
        }
        success {
            echo 'Sucesso ✅'
        }
        failure {
            echo 'Build failed.'
        }
    }
}
