pipeline {
    agent { 
        node('Servidor-ImaginaDev')
    }

    environment {
        GIT_CREDENTIALS = credentials('Token-Github-Integracion')
        REPO_DIR = '/var/www/aramark-dipefa/' 
        RAMA_GIT = 'Develop'
        NODE_IP = ''
        NVM_DIR = "${HOME}/.nvm"
        NODE_VERSION = '20.13.1'
        PM2_NAME = 'aramark'
        PM2_PORT = '8088'
    }

    stages {
        stage('Setup Environment') {
            steps {
                script {
                    NODE_IP = sh(script: "hostname -I | awk '{print \$1}'", returnStdout: true).trim()
                }
            }
        }

        stage('Prepare Node.js Environment') {
            steps {
                script {
                    sh """
                        export NVM_DIR="${NVM_DIR}"
                        [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
                        nvm install ${NODE_VERSION}
                        nvm use ${NODE_VERSION}
                    """
                }
            }
        }

        stage('Git Operations and Setup Node.js Project') {
            steps {
                script {
                    try {
                        def repoExists = fileExists("${REPO_DIR}")

                        if (!repoExists) {
                            sh """
                                git clone -b ${RAMA_GIT} https://${GIT_CREDENTIALS_USR}:${GIT_CREDENTIALS_PSW}@github.com/imaginasoft-chile/aramark-dipefa.git ${REPO_DIR}
                                cd ${REPO_DIR}
                                git checkout ${RAMA_GIT}
                                git fetch https://${GIT_CREDENTIALS_USR}:${GIT_CREDENTIALS_PSW}@github.com/imaginasoft-chile/aramark-dipefa.git
                                git reset --hard FETCH_HEAD
                                export NVM_DIR="${NVM_DIR}"
                                [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
                                nvm use ${NODE_VERSION}
                                cp /imagina/config/aramark/config.js /var/www/aramark-dipefa/lib/config.js
                                npm install
                                pm2 start index.js --name "${PM2_NAME}" --env production -- PORT=${PM2_PORT}
                            """
                            echo "Repositorio clonado y aplicación iniciada en PM2."
                        } else {
                            sh """
                                cd ${REPO_DIR}
                                git checkout ${RAMA_GIT}
                                git fetch https://${GIT_CREDENTIALS_USR}:${GIT_CREDENTIALS_PSW}@github.com/imaginasoft-chile/aramark-dipefa.git
                                git reset --hard FETCH_HEAD
                                export NVM_DIR="${NVM_DIR}"
                                [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
                                nvm use ${NODE_VERSION}
                                cp /imagina/config/aramark/config.js /var/www/aramark-dipefa/lib/config.js
                                npm install
                                pm2 delete ${PM2_NAME}
                                pm2 start index.js --name "${PM2_NAME}" --env production -- PORT=${PM2_PORT}
                            """
                            echo "Repositorio actualizado y aplicación reiniciada en PM2."
                        }
                    } catch (Exception e) {
                        error "Error en Git o PM2: ${e.message}"
                    }
                }
            }
        }

        stage('Notificación Google Chat') {
            steps {
                script {
                    def commitMessage = sh(script: "git -C ${REPO_DIR} log -1 --pretty=format:'%s'", returnStdout: true).trim()
                    def commitAuthor = sh(script: "git -C ${REPO_DIR} log -1 --pretty=format:'%an'", returnStdout: true).trim()

                    def chileTimeZone = java.util.TimeZone.getTimeZone('America/Santiago')
                    def chileDateFormat = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
                    chileDateFormat.setTimeZone(chileTimeZone)
                    def currentDate = chileDateFormat.format(new Date())

                    def jsonPayload = """
                    {
                      "cards": [
                        {
                          "header": {
                            "title": "🚀 Despliegue completado",
                            "subtitle": "Aplicación Aramark-Dipefa"
                          },
                          "sections": [
                            {
                              "widgets": [
                                {
                                  "keyValue": {
                                    "topLabel": "Ambiente",
                                    "content": "<font color=\\\"#1E88E5\\\"><b>DEV</b></font>"
                                  }
                                },
                                {
                                  "keyValue": {
                                    "topLabel": "Fecha",
                                    "content": "${currentDate}"
                                  }
                                },
                                {
                                  "keyValue": {
                                    "topLabel": "Commit",
                                    "content": "${commitMessage}"
                                  }
                                },
                                {
                                  "keyValue": {
                                    "topLabel": "Autor del Commit",
                                    "content": "${commitAuthor}"
                                  }
                                }
                              ]
                            }
                          ]
                        }
                      ]
                    }
                    """

                    sh """
                    curl -X POST \
                      -H 'Content-Type: application/json' \
                      -d '${jsonPayload}' \
                      'https://chat.googleapis.com/v1/spaces/AAAAAm3PtTk/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=OxHKop730Hu-i-jrV9OXoJUCoHyhJsKrJ5JwAfsVrjs'
                    """
                    echo "Notificación enviada a Google Chat correctamente."
                }
            }
        }
    }

    post {
        failure {
            steps {
                script {
                    def subject = "ARAMARK-DIPEFA DESPLIEGUE FALLIDO - DEV"
                    def content = "El despliegue en el servidor falló. Revisar pipeline."
                    echo "[ERROR] ${subject}: ${content}"
                }
            }
        }
    }
}
