pipeline {
    agent any
    environment {
        S3_BUCKET = 's3://ai-enterprise-brain-dev-frontend-bucket/'
        CLOUDFRONT_DISTRIBUTION_ID = 'ETZYYRX2Q6OQN'
        ENV_S3_BUCKET_PATH = 's3://allenvvariables/ai-enterprise-brain-dev/frontend-dev.env'
        NODE_INSTALLATION = 'AI-Deploy'
        ENV = 'v2'
    }
    stages {
        stage('get_commit_msg') {
            steps {
                script {
                    env.GIT_COMMIT_MSG = sh (script: 'git log -1 --pretty=%B ${GIT_COMMIT}', returnStdout: true).trim()
                    GIT_COMMIT_EMAIL = sh (
                        script: 'git --no-pager show -s --format=\'%ae\'',
                        returnStdout: true
                    ).trim()
                    echo "Git committer email: ${GIT_COMMIT_EMAIL}"
                    echo "${GIT_COMMIT_MSG}"
                }
            }
        }
        stage('Setup Environment variables') {
            steps {
                script {
                    sh "aws s3 cp ${ENV_S3_BUCKET_PATH} ./frontend/.env"
                }
            }
        }
        stage('build') {
            steps {
                nodejs("${env.NODE_INSTALLATION}") {
                    echo 'building'
                    dir('frontend') {
                        sh 'npm cache clean --force && npm install --force'
                        sh 'npm run build'
                    }
                }
            }
        }
        stage('deployment') {
            steps {
                script {
                    sh "aws s3 cp ./frontend/dist ${S3_BUCKET} --recursive"
                    sh "aws cloudfront create-invalidation --distribution-id ${CLOUDFRONT_DISTRIBUTION_ID} --paths \"/*\""
                    echo 'Deployment Success'
                }
            }
        }
    }
    post {
       always { 
            script{
                cleanWs()
            }
        }
    }
}