pipeline {
	agent {
		docker {
			image 'hub.davinti.com.br:443/infra/node:latest'
				args '-u 1001:1001 --rm --entrypoint="" -e HOME=${WORKSPACE}'
		}
	}

	environment {
		S3_BUCKET = "s3://app-dono-manifests"
		GIT_TOKEN = credentials('gitea-pat')
	}

	stages {
		stage('Install') {
		    
			steps {
			    sh """
                # Create a .netrc file so Git can find the PAT for your Gitea domain
                echo "machine git.davinti.com.br" > ~/.netrc
                echo "login jenkins" >> ~/.netrc
                echo "password ${GIT_TOKEN}" >> ~/.netrc
                chmod 600 ~/.netrc

				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' "${GIT_TOKEN}"

                npm install
                """
			}
		}

		stage('Vet') {
			steps {
				echo 'Validating modules (Standard for all branches)...'
					sh 'npx jeff vet -i "src/**/*.module.ts" --strict'
			}
		}

		stage('Generate & Upload') {
			when {
				branch 'main'
			}
			steps {
				echo 'Generating manifest and deploying to S3...'
					sh 'npm run generate:output'

					sh 'tar -czvf migrations.tar.gz -C migrations/ .'

					withAWS(credentials: 'aws-jeff-credentials-id', region: 'sa-east-1') {
						script {
							echo "Uploading to S3..."
							sh "aws s3 cp dist/manifest.json ${S3_BUCKET}/manifest.json"
							sh "aws s3 cp migrations.tar.gz ${S3_BUCKET}/migrations.tar.gz"
						}
					}
			}
		}
	}

	post {
		always {
            sh 'rm -rf *'
			script {
				deleteDir()
			}
		}
		success {
            echo "✨ Manifest successfully uploaded to S3!"
        }
        failure {
            echo "❌ Build failed. Check the logs for Jeff's validation errors."
        }
	}
}

