pipeline {
  agent {
    label 'aws'
  }

  options {
    ansiColor('xterm')
    disableConcurrentBuilds()
    timestamps()
    timeout(time: 60, unit: 'MINUTES')
  }

  parameters {
    string(name: 'SHARED_LIBRARIES_VERSION', defaultValue: 'master', description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag, Git revision or PR ref (e.g. pull/PR_NUMBER/merge).')
  }

  triggers {
    issueCommentTrigger('.*retest this please.*')
  }

  environment {
    APP_NAME = 'virtual-sales-rep'
  }

  stages {
    stage('Load Shared Libraries') {
      steps {
        library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
      }
    }

    stage('PR validation') {
      steps {
        checkout scm

        sh '''
          set -eux
          for f in package.json biome.json tsconfig.base.json pnpm-workspace.yaml pnpm-lock.yaml .nvmrc .npmrc .editorconfig README.md Jenkinsfile Jenkinsfile.deploy AGENTS.md GEMINI.md onboard.sh docker/docker-compose.yml docker/scripts/db-reset.sh scripts/ts-check.sh scripts/porting-tally.py docs/CHANGELOG.md docs/FOLLOW_UP_TICKETS.md docs/GRAPHQL_SERVER_PATTERN_AUDIT.md docs/ORCHARD_SUITE_PORTING_ASSESSMENT.md static-analysis.datadog.yml; do
            if [ ! -f "$f" ]; then
              echo MISSING file: $f
              exit 1
            fi
            wc -c "$f"
          done
          for d in .github docker docker/scripts docs infra infra/sql scripts; do
            if [ ! -d "$d" ]; then
              echo MISSING dir: $d
              exit 1
            fi
            find "$d" -maxdepth 2 -type f | head -20
          done
          for sql in infra/sql/001_users_accounts.sql infra/sql/002_cart.sql infra/sql/003_orders.sql infra/sql/004_notifications.sql infra/sql/snowflake-views.sql infra/sql/rds-admin-users.sql infra/sql/rds-admin-users-validate.sql infra/sql/rds-service-users.sql infra/sql/FIELD_MAPPING.txt; do
            if [ ! -s "$sql" ]; then
              echo SQL MISSING OR EMPTY: $sql
              exit 1
            fi
          done
          for sh_script in onboard.sh docker/scripts/db-reset.sh; do
            head -1 "$sh_script" | grep -q "^#!" || { echo MISSING shebang: $sh_script; exit 1; }
          done
        '''

        nodeSh(
          user: 'root',
          script: '''
set -eux
node --version
corepack enable
pnpm --version
pnpm install --frozen-lockfile --reporter=default
pnpm exec biome --version
bash -n scripts/ts-check.sh

# Lint (warnings allowed, errors fail the build)
pnpm --recursive run lint

# Type-check frontend (tsc --noEmit)
pnpm --filter @theorchard/virtual-sales-rep run typecheck

# Unit tests
pnpm --recursive run test
'''
        )
      }
    }
  }

  post {
    success {
      echo "${APP_NAME} PR validation passed."
    }
    failure {
      echo "${APP_NAME} PR validation failed. Check the stage output above."
    }
    unstable {
      echo "${APP_NAME} PR validation completed with warnings."
    }
  }
}
