// =============================================================================
// PLATFORM MARKETING CONTENT - Jenkins Pipeline
// =============================================================================

pipeline {
    agent any

    environment {
        PROJECT_NAME = 'pmc'
        DOCKER_REGISTRY = '72.60.226.4:5000'
        DEPLOY_SERVER = '72.60.226.4'
        DEPLOY_USER = 'deploy'
        VERSION = "${env.BUILD_NUMBER}"
    }

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

        stage('Install & Build') {
            parallel {
                stage('Backend') {
                    steps {
                        dir('apps/backend') {
                            sh 'npm ci && npm run build'
                        }
                    }
                }
                stage('Frontend') {
                    steps {
                        dir('apps/frontend') {
                            sh 'npm ci && npm run build'
                        }
                    }
                }
            }
        }

        stage('Docker Build & Push') {
            when { anyOf { branch 'main'; branch 'develop' } }
            steps {
                script {
                    ['backend', 'frontend'].each { svc ->
                        sh """
                            docker build -t ${DOCKER_REGISTRY}/${PROJECT_NAME}-${svc}:${VERSION} apps/${svc}/
                            docker push ${DOCKER_REGISTRY}/${PROJECT_NAME}-${svc}:${VERSION}
                            docker tag ${DOCKER_REGISTRY}/${PROJECT_NAME}-${svc}:${VERSION} ${DOCKER_REGISTRY}/${PROJECT_NAME}-${svc}:latest
                            docker push ${DOCKER_REGISTRY}/${PROJECT_NAME}-${svc}:latest
                        """
                    }
                }
            }
        }

        stage('Deploy') {
            when { branch 'main' }
            steps {
                input message: '¿Desplegar a Producción?', ok: 'Desplegar'
                sshagent(['deploy-ssh-key']) {
                    sh """
                        ssh -o StrictHostKeyChecking=no ${DEPLOY_USER}@${DEPLOY_SERVER} '
                            cd /opt/apps/pmc
                            docker-compose -f docker/docker-compose.prod.yml pull
                            docker-compose -f docker/docker-compose.prod.yml up -d
                        '
                    """
                }
            }
        }
    }

    post {
        always { cleanWs() }
    }
}
