pipeline {
    agent any

    tools {
        nodejs 'NodeJS 20' 
    }

    environment {
        FRONT_DEST = '/var/www/xeewy.be'
        BACK_DEST = '/var/www/xeewy/backend'
        SERVICE_NAME = 'xeewy-backend'
    }

    stages {
        // --- FRONTEND (Rien ne change ici) ---
        stage('Build Frontend') {
            steps {
                echo '--- Building React Frontend ---'
                dir('frontend') {
                    sh 'npm install'
                    sh 'npm run build'
                }
            }
        }

        stage('Deploy Frontend') {
            steps {
                echo '--- Deploying Frontend ---'
                sh "rm -rf ${FRONT_DEST}/*"
                sh "cp -r frontend/dist/* ${FRONT_DEST}/" 
            }
        }

        // --- BACKEND (C'est ici qu'on change) ---
        stage('Build Backend') {
            steps {
                echo '--- Building TypeScript Backend ---'
                dir('backend') {
                    sh 'npm install'
                    sh 'npm run build' // Compile le TS vers JS (dossier dist/)
                }
            }
        }

        stage('Deploy Backend') {
            steps {
                echo '--- Deploying Backend ---'
                // On copie le dossier compilé (dist) vers le serveur
                sh "rm -rf ${BACK_DEST}/*"
                sh "cp backend/package.json ${BACK_DEST}/"
                sh "cp backend/package-lock.json ${BACK_DEST}/"
                
                // Copie du dossier dist (le résultat de la compilation)
                sh "cp -r backend/dist ${BACK_DEST}/" 
                
                // Installation des dépendances de prod uniquement
                sh "cd ${BACK_DEST} && npm install --production"
            }
        }

        stage('Restart Service') {
            steps {
                echo '--- Restarting Service ---'
                sh "sudo systemctl restart ${SERVICE_NAME}"
            }
        }
    }
}