pipeline {
    agent none

    environment {
        // Hardcoded package URL as requested
        PACKAGE_URL = "https://packagist.org/packages/codekaizen/wp-package-meta-provider-local"
        // Define username as a variable
        PACKAGIST_USERNAME = "AndrewJDawes"
        // Define credentials for API token
    }

    stages {
        stage('Build and Test') {
            matrix {
                axes {
                    axis {
                        name 'PHP_VERSION'
                        values '8.1', '8.2', '8.3', '8.4'
                    }
                }
                agent {
                    dockerfile {
                        filename 'Dockerfile'
                        dir '.'
                        additionalBuildArgs "--target test --build-arg PHP_VERSION=${PHP_VERSION}"
                        reuseNode false
                    }
                }
                stages {
                    stage('Run Static Analysis and Tests') {
                        steps {
                            sh "composer install"
                            sh "composer run analyze"
                            sh "composer run test"
                            sh "composer run sniff"
                        }
                    }
                }
            }
        }

        stage('Update Packagist') {
            agent any
            steps {
                withCredentials([conjurSecretCredential(credentialsId: 'andrewjdawes-packagist-api-token', variable: 'PACKAGIST_API_TOKEN')]) {
                    script {
                        echo "Notifying Packagist of new changes"
                        sh '''
                            curl -XPOST -H "content-type:application/json" \
                            "https://packagist.org/api/update-package?username=${PACKAGIST_USERNAME}&apiToken=${PACKAGIST_API_TOKEN}" \
                            -d "{\\\"repository\\\":{\\\"url\\\":\\\"${PACKAGE_URL}\\\"}}"
                        '''
                    }
                }
            }
        }
    }

    post {
        success {
            echo "Successfully updated package on Packagist"
        }
        failure {
            echo "Failed to update package on Packagist"
        }
    }
}
