pipeline {
  // Build + deploy stages require Docker CLI/daemon access on the Jenkins node.
  // Ensure this label maps to an agent with Docker installed and usable.
  //update
  agent any

  environment {
    REGISTRY_IMAGE = "plesk-agency-portal"
    IMAGE_LATEST = "${REGISTRY_IMAGE}:latest"
    IMAGE_BUILD = "${REGISTRY_IMAGE}:build-${BUILD_NUMBER}"
    DEPLOY_SSH_CREDENTIAL_ID = "${env.DEPLOY_SSH_CREDENTIAL_ID ?: 'plesk-agency-deploy-key'}"
    APP_HOST = "${env.APP_HOST ?: '192.168.68.89'}"
    APP_USER = "${env.APP_USER ?: 'deploy'}"
    DEPLOY_PATH = "${env.DEPLOY_PATH ?: '/opt/plesk-agency-portal'}"
    APP_BASE_URL = "${env.APP_BASE_URL ?: 'http://192.168.68.89:3000'}"

  }

  stages {
    // stage('Preflight') {
    //   steps {
    //     sh '''
    //       set -euo pipefail

    //       if ! command -v docker >/dev/null 2>&1; then
    //         echo "Docker CLI is not available on this Jenkins agent."
    //         echo "Run this pipeline on a Docker-capable node or install Docker on the current agent."
    //         exit 1
    //       fi

    //       if ! docker version >/dev/null 2>&1; then
    //         echo "Docker is installed but not usable by Jenkins (daemon/socket/permissions issue)."
    //         exit 1
    //       fi
    //     '''
    //   }
    // }

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

    stage('Install dependencies') {
      steps {
        sh 'npm ci'
      }
    }

    // stage('Lint') {
    //   steps {
    //     script {
    //       def hasLint = sh(script: "node -e \"const fs=require('fs');const p=require('./package.json');process.exit(p?.scripts?.lint?0:1)\"", returnStatus: true)
    //       if (hasLint == 0) {
    //         sh 'npm run lint'
    //       } else {
    //         echo 'No lint script configured; skipping lint stage.'
    //       }
    //     }
    //   }
    // }

    stage('Build application') {
      steps {
        withCredentials([
          string(credentialsId: 'supabase-public-url', variable: 'NEXT_PUBLIC_SUPABASE_URL'),
          string(credentialsId: 'supabase-public-anon-key', variable: 'NEXT_PUBLIC_SUPABASE_ANON_KEY')
        ]) {
          sh 'npm run build'
        }
      }
    }

    stage('Build Docker image') {
      steps {
        withCredentials([
          string(credentialsId: 'supabase-public-url', variable: 'NEXT_PUBLIC_SUPABASE_URL'),
          string(credentialsId: 'supabase-public-anon-key', variable: 'NEXT_PUBLIC_SUPABASE_ANON_KEY')
        ]) {
          sh 'docker build --build-arg NEXT_PUBLIC_SUPABASE_URL="$NEXT_PUBLIC_SUPABASE_URL" --build-arg NEXT_PUBLIC_SUPABASE_ANON_KEY="$NEXT_PUBLIC_SUPABASE_ANON_KEY" --build-arg BUILD_CACHE_BUSTER="${BUILD_NUMBER}" -t ${IMAGE_LATEST} -t ${IMAGE_BUILD} .'
        }
      }
    }

stage('Deploy') {
  steps {
    withCredentials([sshUserPrivateKey(
      credentialsId: "${env.DEPLOY_SSH_CREDENTIAL_ID}",
      keyFileVariable: 'SSH_KEY'
    )]) {
      sh '''
bash <<EOF
set -euxo pipefail

SSH_OPTS="-i ${SSH_KEY} -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"

echo "Testing remote SSH connectivity"
ssh ${SSH_OPTS} "${APP_USER}@${APP_HOST}" "whoami && hostname && pwd"

echo "Deploying image tag: ${IMAGE_BUILD}"
docker image inspect "${IMAGE_BUILD}" --format='{{.Id}} {{.RepoTags}}'

ssh ${SSH_OPTS} "$APP_USER@$APP_HOST" "mkdir -p $DEPLOY_PATH/scripts"

rsync -az \
  -e "ssh ${SSH_OPTS}" \
  docker-compose.prod.yml \
  "$APP_USER@$APP_HOST:$DEPLOY_PATH/"

rsync -az \
  -e "ssh ${SSH_OPTS}" \
  scripts/ \
  "$APP_USER@$APP_HOST:$DEPLOY_PATH/scripts/"

IMAGE_TAR="plesk-agency-portal-build.tar"
echo "Creating image archive: ${IMAGE_TAR}"
docker save -o "${IMAGE_TAR}" "${IMAGE_BUILD}"
ls -lh "${IMAGE_TAR}"
sha256sum "${IMAGE_TAR}"

echo "Copying image archive to remote host via scp"
scp ${SSH_OPTS} "${IMAGE_TAR}" "$APP_USER@$APP_HOST:$DEPLOY_PATH/"

echo "Verifying image archive exists on remote host"
ssh ${SSH_OPTS} "$APP_USER@$APP_HOST" "ls -lh $DEPLOY_PATH/plesk-agency-portal-build.tar"
ssh ${SSH_OPTS} "$APP_USER@$APP_HOST" "sha256sum $DEPLOY_PATH/plesk-agency-portal-build.tar"

echo "Loading image archive on remote host"
ssh ${SSH_OPTS} "$APP_USER@$APP_HOST" "docker load -i $DEPLOY_PATH/plesk-agency-portal-build.tar"

echo "Verifying exact image tag is available on remote host"
ssh ${SSH_OPTS} "$APP_USER@$APP_HOST" "docker image inspect ${IMAGE_BUILD} --format='{{.Id}} {{.RepoTags}}'"

ssh ${SSH_OPTS} "$APP_USER@$APP_HOST" \
  "cd $DEPLOY_PATH && chmod +x ./scripts/deploy-prod.sh ./scripts/smoke-check.sh ./scripts/rollback-prod.sh"

echo "Running remote deploy script with exact image tag"
ssh ${SSH_OPTS} "$APP_USER@$APP_HOST" \
  "cd $DEPLOY_PATH && APP_IMAGE='${IMAGE_BUILD}' ./scripts/deploy-prod.sh"

echo "Printing final running container image metadata"
ssh ${SSH_OPTS} "$APP_USER@$APP_HOST" "docker inspect plesk-agency-portal --format='{{.Image}} {{.Created}}'"
EOF
      '''
    }
  }
}

    stage('Smoke check') {
      steps {
        sh '''
bash -eo pipefail << EOF
set -euo pipefail
chmod +x scripts/smoke-check.sh
scripts/smoke-check.sh "${APP_BASE_URL}"
EOF
'''
      }
    }
  }
}
