// Apollo MCP Server CI/CD.
// Builds + scans the image and deploys to the apollo-mcp Fargate service.
// NOTE: deploy stages need the ECR repo + apollo-mcp Fargate services to exist
// (GQL-349 terraform-infra). The `ci-lint-test` make target is not added yet.

String GITHUB_REPOSITORY = 'apollo-mcp'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#graphql'
String QA_ACCOUNT_ID = '437795906767'
String QA_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String PROD_ACCOUNT_ID = '437795906767'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'

// curl in the debian13 parent is 8.14.1-2+deb13u3 (security-patched). The scanner
// reports it as pkg:generic and reads only the base 8.14.1, so it can't see the
// Debian backport and flags CVE-2026-5773 (fixed upstream in 8.20.0, which no Debian
// stable ships). curl is used only for the localhost /health probe. Drop this once
// the parent image carries curl >= 8.20.0.
List<String> VULNERABILITIES_TO_IGNORE = ['CVE-2026-5773']

pipeline {
    agent any

    options {
        ansiColor('xterm')
        disableConcurrentBuilds()
        timestamps()
    }

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, description: 'Whether or not to deploy to prod.')
        string(name: 'SHARED_LIBRARIES_VERSION', defaultValue: 'master', description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag, Git revision or PR ref (e.g. pull/PR_NUMBER/merge).')
    }

    triggers {
        issueCommentTrigger('.*retest this please.*')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }

        stage('Compliance Checks') {
            steps {
                complianceChecks()
            }
        }

        stage('Build Test and Scan') {
            parallel {
                stage('Validate Software Catalog Definition') {
                    steps {
                        datadogSoftwareCatalogValidate()
                    }
                }

                stage('Unit Tests and Style Checks') {
                    environment {
                        COMPOSE_PROJECT_NAME = "${env.BUILD_TAG.toLowerCase()}"
                    }
                    steps {
                        withEcr {
                            sh 'make ci-lint-test'
                        }
                    }
                }

                stage('Static Application Security Tests') {
                    steps {
                        sastTests()
                    }
                }

                // No Sonar Scan stage: apollo-mcp ships YAML config + GraphQL operations,
                // not a compiled/scriptable source language Sonar can analyze. Re-add with a
                // valid `language` if real application source lands here.

                stage('Create and Scan a Release') {
                    steps {
                        dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY,
                            imageTag: env.GIT_COMMIT, dockerBuildTarget: 'deploy', dockerBuildCacheDisabled: false
                        dockerScan awsRegion: AWS_REGIONS[0], ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY,
                            imageTag: env.GIT_COMMIT, vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                    }
                }
            }
        }

        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                fargateDeploy environment: 'qa', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
                    ecrRegistryAccountId: ECR_ACCOUNT_ID, awsDeploymentTargetAccountId: QA_ACCOUNT_ID, awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
            }
        }

        // No integration / E2E tests in this repo.
        // stage('Integration Tests') {
        //     when {
        //         branch 'master'
        //     }
        //     steps {
        //         withEcr {
        //             sh 'make ci_test_integration'
        //         }
        //     }
        // }

        stage('Deploy to Prod') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
        //         fargateDeploy environment: 'prod', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
        //             ecrRegistryAccountId: ECR_ACCOUNT_ID, awsDeploymentTargetAccountId: PROD_ACCOUNT_ID, awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                datadogSoftwareCatalogPublish()
            }
        }
    }

    post {
        always {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        cleanup {
            cleanWs()
        }
    }
}
