name: Deploy on Master Change
on:
  push:
    branches:
      - master
  pull_request:
    types: [opened, synchronize, reopened]
    branches:
      - master

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code (with full history + correct branch)
        uses: actions/checkout@v4
        with:
          fetch-depth: 0       # Lấy toàn bộ history
          ref: master          # Đảm bảo checkout đúng branch master

      - name: Deploy to server
        env:
          SSH_IP: ${{ secrets.SSH_IP }}
          SSH_PORT: ${{ secrets.SSH_PORT }}
          SSH_USER: ${{ secrets.SSH_USER }}
          SSH_PASS: ${{ secrets.SSH_PASSWORD }}
        run: |
          # Cài sshpass
          sudo apt-get update -y
          sudo apt-get install -y sshpass

          echo "Đang deploy lên server..."

          sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no -p "$SSH_PORT" "$SSH_USER@$SSH_IP" << 'EOF'
            set -e

            cd /var/www/rikkei_simple_care

            echo "Force update code từ remote (hỗ trợ cả force push)"
            git fetch --all
            git reset --hard origin/master
            git clean -fd

            # Load NVM for node/npm
            export NVM_DIR="$HOME/.nvm"
            [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

            echo "Build management frontend..."
            cd management
            npm install
            VITE_API_BASE=https://sv.rikkeiraia.org/api npm run build
            cd ..

            echo "Build storage server..."
            cd storage_server
            npm install
            npm run build
            pm2 delete storage_server || true
            pm2 start dist/main.js --name storage_server
            cd ..

            echo "Build server backend..."
            cd server
            go build -o serverlinux main.go
            pm2 delete raia_v3_server || pm2 delete serverlinux || true
            pm2 start ./serverlinux --name raia_v3_server
            cd ..

            pm2 save  # lưu lại trạng thái pm2

            echo "Deploy thành công!"
          EOF