pipeline {
  agent {
    docker {
      image 'node:20'
      args '-v /var/run/docker.sock:/var/run/docker.sock'
    }
  }

  environment {
    REGISTRY = 'registry.wk-archi-o24a-15m-g3.fr'
    BACK_IMAGE = "${REGISTRY}/the-tip-top-backend"
  }

  stages {

    stage('Checkout') {
      steps {
        git branch: 'main', url: 'https://gitea.wk-archi-o24a-15m-g3.fr/wkadmin/the-tip-top-backend.git'
      }
    }

    stage('Build Backend Image') {
      steps {
        sh '''
          echo "📦 Installation des dépendances..."
          npm install

          echo "🐳 Construction de l’image Docker backend..."
          docker build -t $BACK_IMAGE:latest .
        '''
      }
    }

    stage('Push Image to Registry') {
      steps {
        withCredentials([usernamePassword(credentialsId: 'gitea-registry', usernameVariable: 'USER', passwordVariable: 'PASS')]) {
          sh '''
            echo "🔑 Connexion au registre..."
            docker login $REGISTRY -u $USER -p $PASS

            echo "📤 Push de l’image vers le registre..."
            docker push $BACK_IMAGE:latest
          '''
        }
      }
    }

    stage('Deploy Backend on VPS') {
      steps {
        sshagent(['vps-ssh-key']) {
          sh '''
            echo "🚀 Déploiement du backend sur le VPS..."
            ssh -o StrictHostKeyChecking=no debian@51.75.24.29 "
              cd /srv/devops/the-tip-top &&
              docker compose pull backend &&
              docker compose up -d --build backend
            "
          '''
        }
      }
    }
  }

  post {
    success {
      echo "✅ Backend déployé avec succès !"
    }
    failure {
      echo "❌ Échec du pipeline Backend — vérifier les logs Jenkins."
    }
  }
}
