pipeline {
  agent {
    docker {
      image 'cimg/node:18.18.2'
      args '-v /root/jenkins/data/jobs/${JOB_NAME}/data/node_modules:${WORKSPACE}/node_modules -v /var/run/docker.sock:/var/run/docker.sock -v /usr/bin/docker:/usr/bin/docker'
    }
  }
  stages {
    stage('BUILD PROJECT') {
      steps {
        sh '''
          npm set registry https://registry.npmmirror.com/
          npm install -g pnpm 
          node -v
          pnpm -v
          pnpm install
          pnpm run build
          cp -r ./dist ./build
        '''
      }
    }
    stage('BUILD IMAGE') {
      steps {
        sh '''
          cd build
          docker build -t $registry_address/$image_name:latest .'''
      }
    }
    stage('PUSH IMAGE') {
        steps {
          sh '''docker login -u deployment -p deployment123 $registry_address
          docker push $registry_address/$image_name:latest'''
        }
    }
    stage('Deploy to SIT') {
        steps {
            sh '''# docker-compose pull env
            curl -X PUT http://$app_server_sit/api/v1/projects --data \'{"id":"\'$app_project_name\'"}\' -H\'Content-type: application/json\''''
            sh '''# docker-compose up
            curl -X POST http://$app_server_sit/api/v1/projects --data \'{"id":"\'$app_project_name\'"}\' -H\'Content-type: application/json\''''
        }
    }
    stage('REMOVE LOCAL IMAGE') {
        steps {
          sh '''docker rmi -f $registry_address/$image_name:latest'''
        }
    }
    stage('Cleanup') {
      steps {
        cleanWs(deleteDirs: true)
      }
    }
  }
  environment {
    registry_address = 'nexus3.gsstcloud.com:8092/marketing-ai'
    image_name = 'marketingai-edu-fe'
    app_server_sit = '192.168.21.102:5000'
    app_project_name = 'marketingai-edu'
  }
}
