pipeline {
  agent any

  environment {
    REGISTRY     = 'docker.io/camelsoft801'
    IMAGE_TAG    = "build-${env.BUILD_NUMBER}"
    DOCKER_CRED  = 'docker-hub'
    DEPLOY_HOSTS = "134.122.91.192 165.227.164.39"
  }

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

    stage('Debug checkout') {
      steps {
        sh 'echo "===== on branch: $(git rev-parse --abbrev-ref HEAD)"'
        sh 'echo "===== last commit: $(git log -1 --oneline)"'
      }
    }

    stage('Compile & unit test') {
      steps {
        sh 'chmod +x mvnw'
        sh './mvnw -B clean package -DskipTests'
      }
    }

    stage('Pre-flight') {
      steps {
        sh 'find . -name mvnw -exec chmod +x {} \\;'
      }
    }

    stage('Docker login') {
      steps {
        withCredentials([usernamePassword(
          credentialsId: env.DOCKER_CRED,
          usernameVariable: 'HUB_USER',
          passwordVariable: 'HUB_PASS'
        )]) {
          sh 'echo "$HUB_PASS" | docker login -u "$HUB_USER" --password-stdin'
        }
      }
    }

    stage('Docker build & push') {
      steps {
        script {
          // Use a map for service names and their corresponding directory paths for clarity
          def servicePathMap = [
            'eureka-server': 'eureka-server',
            'config-server': 'config-server',
            'api-gateway': 'api-gateway',
            'admin-service': 'admin-service',
            'auth-service': 'auth-service',
            'client-service': 'client-service',
            'common-service': 'common',
            'corporate-service': 'corporate-service',
            'driver-service': 'driver-service',
            'invoices-service': 'invoices',
            'location-service': 'location-service',
            'notification-service': 'notification-service',
            'pricing-service': 'pricing-service',
            'report-service': 'report-service',
            'ride-service': 'ride-service'
          ]

          servicePathMap.each { serviceName, directoryPath ->
            echo "Building and pushing ${serviceName} from path ${directoryPath}"
            sh """
              docker build --pull -t ${REGISTRY}/${serviceName}:${IMAGE_TAG} ${directoryPath}
              docker push ${REGISTRY}/${serviceName}:${IMAGE_TAG}
            """
          }
        }
      }
    }

    stage('Prepare env file') {
      steps {
        writeFile file: 'env.deploy', text: """\
REGISTRY=${REGISTRY}
IMAGE_TAG=${IMAGE_TAG}
"""
      }
    }

    stage('Deploy to droplets') {
      steps {
        sshagent(credentials: ['beem-ssh-key']) {
          script {
            for (host in DEPLOY_HOSTS.split()) {
              echo "📦 Deploying to ${host}…"

              // Clean & recreate remote dir
              sh "ssh -o StrictHostKeyChecking=no root@${host} 'rm -rf /opt/beem && mkdir -p /opt/beem'"

              // Copy compose + env file ONLY
              sh """
                scp -o StrictHostKeyChecking=no \\
                  "${env.WORKSPACE}/docker-compose.yml" \\
                  "${env.WORKSPACE}/env.deploy" \\
                  root@${host}:/opt/beem/
              """

              // Rename env.deploy → .env
              sh "ssh -o StrictHostKeyChecking=no root@${host} 'mv /opt/beem/env.deploy /opt/beem/.env'"

              // Pull & start services in a controlled sequence
              sh """
                ssh -o StrictHostKeyChecking=no root@${host} "
                  cd /opt/beem &&
                  echo 'Pruning old images and volumes…' &&
                  docker system prune -af &&
                  docker volume prune -f &&
                  echo 'Pulling latest images…' &&
                  docker compose pull &&
                  echo 'Starting all services except the API Gateway...' &&
                  docker compose up -d --remove-orphans --scale api-gateway=0 &&
                  echo 'Waiting 60 seconds for services to initialize and register with Eureka...' &&
                  sleep 60 &&
                  echo 'Starting the API Gateway...' &&
                  docker compose up -d api-gateway &&
                  echo 'Deployment sequence complete. Checking status...' &&
                  sleep 20 &&
                  docker compose logs --tail=100 eureka-server &&
                  docker compose logs --tail=100 api-gateway &&
                  docker compose ps
                "
              """
            }
          }
        }
      }
    }
  }

  post {
    always {
      cleanWs()
    }
  }
}
