pipeline {
  agent any
  environment {
    AWS_REGION = 'us-east-1'
    ECR_REPO = "${env.ECR_REPO ?: '123456789012.dkr.ecr.us-east-1.amazonaws.com/cloudops-app'}"
    IMAGE_TAG = "${env.BUILD_NUMBER ?: 'local'}"
    KUBECONFIG = credentials('kubeconfig-credential-id') // store kubeconfig in Jenkins credentials
  }
  stages {
    stage('Checkout') {
      steps {
        checkout scm
      }
    }
    stage('Build Docker Image') {
      steps {
        sh 'docker build -t ${ECR_REPO}:${IMAGE_TAG} services/app'
      }
    }
    stage('ECR Login & Push') {
      steps {
        sh '''
          aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin ${ECR_REPO%/*}
          docker push ${ECR_REPO}:${IMAGE_TAG}
        '''
      }
    }
    stage('Deploy to Kubernetes') {
      steps {
        withCredentials([file(credentialsId: 'kubeconfig-credential-id', variable: 'KUBEF')]) {
          sh 'export KUBECONFIG=$KUBEF'
          sh "kubectl -n cloudops set image deployment/cloudops-app cloudops-app=${ECR_REPO}:${IMAGE_TAG} || kubectl apply -f k8s/app-deployment.yaml"
          sh 'kubectl rollout status deployment/cloudops-app -n cloudops --timeout=120s'
        }
      }
    }
  }
  post {
    success { echo 'Deployed successfully' }
    failure { echo 'Pipeline failed' }
  }
}
