pipeline {
    agent any

    stages {
        stage('Build backend') {
            steps {
                sh "whoami"
                sh "echo $PATH"
                sh 'export PATH="$PATH:/var/lib/jenkins/.local/share:/var/lib/jenkins/.cargo/bin/"'
                sh "echo $PATH"
                sh "which cargo"
                sh "cd ${env.WORKSPACE}/backend"
                sh "cargo build --release"
            }
        }
        stage('Build frontend') {
            steps {
                sh "cd ${env.WORKSPACE}/frontend"
                sh "pnpm i"
                sh "pnpm build"
            }
        }
        stage("Create ENV file") {
            steps {
                sh "cd ${env.WORKSPACE}"
                sh "touch .env"
                sh "echo DATABASE_URL=mysql://educa7ls_user:123456789a*@md-89.webhostbox.net:3306/educa7ls_plataforma >> .env"
                sh "echo RENIEC_API=apis-token-1.aTSI1U7KEuT-6bbbCguH-4Y8TI6KS73N >> .env"
            }
        }
        stage("Stop old PM2 processes") {
            steps {
                sh "pm2 stop ${env.JOB_BASE_NAME} || true"
                sh "pm2 delete ${env.JOB_BASE_NAME} || true"
            }
        }
        stage("Clean deploy folder") {
            steps {
                sh "rm -rf /var/deploys/${env.JOB_BASE_NAME}/* || true"
            }
        }
        stage("Copy deploy files") {
            steps {
                sh "mkdir -p /var/deploys/${env.JOB_BASE_NAME}/${env.BUILD_TAG}/static"
                // Copy backend binary
                sh "cp ${env.WORKSPACE}/backend/target/release/backend /var/deploys/${env.JOB_BASE_NAME}/${env.BUILD_TAG}/"
                // Copy frontend static files
                sh "cp -r ${env.WORKSPACE}/frontend/dist/* /var/deploys/${env.JOB_BASE_NAME}/${env.BUILD_TAG}/static/"
                // Copy ENV file
                sh "cp ${env.WORKSPACE}/.env /var/deploys/${env.JOB_BASE_NAME}/${env.BUILD_TAG}/"
            }
        }
        stage('Start app with PM2') {
            steps {
                sh "cd /var/deploys/${env.JOB_BASE_NAME}/${env.BUILD_TAG}/"
                // ROCKET_PORT=3333
                sh "pm2 start backend --name ${env.JOB_BASE_NAME}"
            }
        }
    }
}
