// camel-soft.com — lead API pipeline.
// Builds the Spring Boot jar, publishes it to /opt/camelsoft-website-api and
// restarts only this service. Port 8090, nothing else on the server is touched.
pipeline {
  agent any

  options {
    timestamps()
    disableConcurrentBuilds()
    buildDiscarder(logRotator(numToKeepStr: '15'))
    timeout(time: 20, unit: 'MINUTES')
  }

  environment {
    APP_DIR  = '/opt/camelsoft-website-api'
    SERVICE  = 'camelsoft-website-api'
    HEALTH   = 'http://127.0.0.1:8090/actuator/health'
  }

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

    stage('Build') {
      steps { sh 'mvn -B -ntp -DskipTests clean package' }
    }

    stage('Deploy') {
      steps {
        sh '''
          JAR=$(ls target/website-api-*.jar | head -1)
          echo "publishing $JAR"
          cp "$JAR" "$APP_DIR/app.jar.new"
          mv -f "$APP_DIR/app.jar.new" "$APP_DIR/app.jar"
          sudo /bin/systemctl restart "$SERVICE"
        '''
      }
    }

    stage('Health check') {
      steps {
        sh '''
          for i in $(seq 1 30); do
            sleep 3
            if curl -fsS "$HEALTH" | grep -q '"status":"UP"'; then
              echo "API is UP"; exit 0
            fi
          done
          echo "API did not become healthy — check: journalctl -u $SERVICE / /var/log/camelsoft-website-api/app.log"
          exit 1
        '''
      }
    }
  }

  post {
    failure { echo 'Build or health check failed — the previous jar is still on disk.' }
  }
}
