pipeline {
    agent any

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

        stage('Build CI Image') {
            steps {
                sh 'docker compose -f docker-compose.ci.yml build --pull'
            }
        }

        stage('Install Dependencies') {
            steps {
                sh 'docker compose -f docker-compose.ci.yml run --rm app composer install --no-interaction --prefer-dist --no-progress'
            }
        }

        stage('Prepare Test DB') {
            steps {
                sh 'docker compose -f docker-compose.ci.yml run --rm app sh -lc \"mkdir -p database && touch database/database.sqlite\"'
            }
        }

        stage('Run Tests') {
            steps {
                script {
                    env.APP_KEY = sh(
                        returnStdout: true,
                        script: "php -r 'echo \"base64:\" . base64_encode(random_bytes(32));'"
                    ).trim()
                }
                sh 'APP_KEY=$APP_KEY docker compose -f docker-compose.ci.yml run --rm app php artisan test'
            }
        }
    }

    post {
        always {
            sh 'docker compose -f docker-compose.ci.yml down -v --remove-orphans'
        }
    }
}
