pipeline {
  agent any

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

  environment {
    AWS_PROFILE       = 'tesi'
    AWS_REGION        = 'eu-west-1'
    CDK_DEPLOY_REGION = 'eu-west-1'
    CDK_DEPLOY_ACCOUNT= '409892200739'
    NODE_OPTIONS      = '--max_old_space_size=4096'
    REPORTS_BUCKET    = 'banu-pipeline-reports'
  }

  stages {

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

    stage('Bootstrap') {
      steps {
        powershell '''
          $ErrorActionPreference = "Stop"

          Write-Host "Node version:"
          node -v
          Write-Host "NPM version:"
          npm -v

          npm install -g aws-cdk
          npm install -g mocha ts-node typescript

          if (Test-Path ".\\cefriel-platform-sdk") {
            npm install .\\cefriel-platform-sdk
          } else {
            Write-Host "cefriel-platform-sdk not found at repo root (skipping)"
          }
        '''
      }
    }

    // Added: AWS SSO Login (once)
    stage('AWS SSO Login') {
      steps {
        powershell '''
          $ErrorActionPreference = "Stop"

          Write-Host "AWS CLI version:"
          aws --version

          Write-Host "Logging in with AWS SSO profile: $env:AWS_PROFILE"
          aws sso login --profile $env:AWS_PROFILE

          Write-Host "Verifying AWS identity..."
          aws sts get-caller-identity --profile $env:AWS_PROFILE --region $env:AWS_REGION
        '''
      }
    }

    stage('Unit Tests') {
      parallel {
        stage('unit: database') {
          steps { dir('database') { powershell 'npm install; npm run test:unit; npm run upload:unit' } }
        }
        stage('unit: vpc') {
          steps { dir('vpc') { powershell 'npm install; npm run test:unit; npm run upload:unit' } }
        }
        stage('unit: ingestor') {
          steps { dir('ingestor') { powershell 'npm install; npm run test:unit; npm run upload:unit' } }
        }
        stage('unit: auth') {
          steps { dir('auth') { powershell 'npm install; npm run test:unit; npm run upload:unit' } }
        }
        stage('unit: api') {
          steps { dir('api') { powershell 'npm install; npm run test:unit; npm run upload:unit' } }
        }
        stage('unit: request-storage') {
          steps { dir('request-storage') { powershell 'npm install; npm run test:unit; npm run upload:unit' } }
        }
        stage('unit: websocket') {
          steps { dir('websocket') { powershell 'npm install; npm run test:unit; npm run upload:unit' } }
        }
      }
    }

    stage('Sonar') {
      when { branch 'master' }
      steps {
        powershell '''
          $ErrorActionPreference = "Continue"
          try {
            sonar-scanner | Tee-Object -FilePath sonar-output.log
          } catch {
            Write-Host "Sonar failed or sonar-scanner not installed (continuing)"
          }

          # If sonar-output.log exists, upload it using the same SSO profile
          if (Test-Path ".\\sonar-output.log") {
            aws s3 cp sonar-output.log s3://$env:REPORTS_BUCKET/sonarqube/output.log --profile $env:AWS_PROFILE --region $env:AWS_REGION
          }
        '''
      }
    }

    stage('Deploy: VPC') {
      steps {
        dir('vpc') {
          powershell '''
            $ErrorActionPreference = "Stop"
            npm install
            cdk bootstrap aws://$env:CDK_DEPLOY_ACCOUNT/$env:CDK_DEPLOY_REGION --profile $env:AWS_PROFILE
            cdk deploy --require-approval never --profile $env:AWS_PROFILE
          '''
        }
      }
    }

    stage('Deploy: Database') {
      options { timeout(time: 30, unit: 'MINUTES') }
      steps {
        dir('database') {
          powershell '''
            $ErrorActionPreference = "Stop"
            npm install
            cdk bootstrap aws://$env:CDK_DEPLOY_ACCOUNT/$env:CDK_DEPLOY_REGION --profile $env:AWS_PROFILE
            cdk deploy --require-approval never --profile $env:AWS_PROFILE
          '''
        }
      }
    }

    stage('Deploy: Auth') {
      steps {
        dir('auth') {
          powershell '''
            $ErrorActionPreference = "Stop"
            npm install
            cdk bootstrap aws://$env:CDK_DEPLOY_ACCOUNT/$env:CDK_DEPLOY_REGION --profile $env:AWS_PROFILE
            cdk deploy --require-approval never --profile $env:AWS_PROFILE
          '''
        }
      }
    }

    stage('Deploy: API') {
      steps {
        dir('api') {
          powershell '''
            $ErrorActionPreference = "Stop"
            npm install
            cdk bootstrap aws://$env:CDK_DEPLOY_ACCOUNT/$env:CDK_DEPLOY_REGION --profile $env:AWS_PROFILE
            cdk deploy --require-approval never --profile $env:AWS_PROFILE
          '''
        }
      }
    }

    stage('Deploy: Request Storage') {
      steps {
        dir('request-storage') {
          powershell '''
            $ErrorActionPreference = "Stop"
            npm install
            cdk bootstrap aws://$env:CDK_DEPLOY_ACCOUNT/$env:CDK_DEPLOY_REGION --profile $env:AWS_PROFILE
            cdk deploy --require-approval never --profile $env:AWS_PROFILE
          '''
        }
      }
    }

    stage('Deploy: Websocket') {
      steps {
        dir('websocket') {
          powershell '''
            $ErrorActionPreference = "Stop"
            npm install
            cdk bootstrap aws://$env:CDK_DEPLOY_ACCOUNT/$env:CDK_DEPLOY_REGION --profile $env:AWS_PROFILE
            cdk deploy --require-approval never --profile $env:AWS_PROFILE
          '''
        }
      }
    }

    stage('Deploy: Ingestor') {
      steps {
        dir('ingestor') {
          powershell '''
            $ErrorActionPreference = "Stop"
            npm install
            cdk bootstrap aws://$env:CDK_DEPLOY_ACCOUNT/$env:CDK_DEPLOY_REGION --profile $env:AWS_PROFILE
            cdk deploy --require-approval never --profile $env:AWS_PROFILE
          '''
        }
      }
    }

    stage('E2E Tests') {
      parallel {
        stage('e2e: websocket') {
          steps { dir('websocket') { powershell 'npm install; npm run test:e2e; npm run upload:e2e' } }
        }
        stage('e2e: database') {
          steps { dir('database') { powershell 'npm install; npm run test:e2e; npm run upload:e2e' } }
        }
        stage('e2e: vpc') {
          steps { dir('vpc') { powershell 'npm install; npm run test:e2e; npm run upload:e2e' } }
        }
        stage('e2e: api') {
          steps { dir('api') { powershell 'npm install; npm run test:e2e; npm run upload:e2e' } }
        }
        stage('e2e: auth') {
          steps { dir('auth') { powershell 'npm install; npm run test:e2e; npm run upload:e2e' } }
        }
        stage('e2e: request-storage') {
          steps { dir('request-storage') { powershell 'npm install; npm run test:e2e; npm run upload:e2e' } }
        }
        stage('e2e: ingestor') {
          steps { dir('ingestor') { powershell 'npm install; npm run test:e2e; npm run upload:e2e' } }
        }
      }
    }

    stage('Report: Consolidated') {
      steps {
        dir('consolidated-report') {
          powershell 'npm install; node generate-report.js'
        }
      }
    }

    stage('Report: Deploy CI Reporting') {
      steps {
        dir('ci-reporting') {
          powershell '''
            $ErrorActionPreference = "Stop"
            npm install
            npm install -g aws-cdk
            cdk deploy --require-approval never --profile $env:AWS_PROFILE
          '''
        }
      }
    }
  }

  post {
    always {
      archiveArtifacts artifacts: '**/sonar-output.log', allowEmptyArchive: true
      junit testResults: '**/test-results/*.xml', allowEmptyResults: true
    }
  }
}
