name: Deploy Max Bot Test

on:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Setup SSH
        env:
          SSH_KEY: ${{ vars.SSH_PRIVATE_KEY }}
        run: |
          mkdir -p ~/.ssh
          echo "$SSH_KEY" | sed 's/^[[:space:]]*//' > ~/.ssh/id_rsa
          chmod 600 ~/.ssh/id_rsa
          ssh-keyscan -p ${{ vars.SERVER_PORT }} ${{ vars.SERVER_HOST }} >> ~/.ssh/known_hosts

      - name: Clone or pull on server
        run: |
          ssh -i ~/.ssh/id_rsa -p ${{ vars.SERVER_PORT }} ${{ vars.SERVER_USER }}@${{ vars.SERVER_HOST }} "
            if [ -d /home/pkirillw/dockered-services/max-bot-test/.git ]; then
              cd /home/pkirillw/dockered-services/max-bot-test && git pull origin main
            else
              cd /home/pkirillw/dockered-services && git clone https://git.pkirillw-server.ru/pkirillw/max-bot-test.git
            fi"

      - name: Create .env file
        env:
          BOT_TOKEN: ${{ secrets.BOT_TOKEN }}
          MAX_BOT_API_SECRET: ${{ secrets.MAX_BOT_API_SECRET }}
          WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
          WEB_APP_URL: ${{ vars.WEB_APP_URL }}
          DEBUG_CHAT_ID: ${{ vars.DEBUG_CHAT_ID }}
          SELFTEST_CHAT_ID: ${{ vars.SELFTEST_CHAT_ID }}
        run: |
          ssh -i ~/.ssh/id_rsa -p ${{ vars.SERVER_PORT }} ${{ vars.SERVER_USER }}@${{ vars.SERVER_HOST }} "cat > /home/pkirillw/dockered-services/max-bot-test/.env << 'ENVEOF'
          BOT_TOKEN=$BOT_TOKEN
          MAX_BOT_API_SECRET=$MAX_BOT_API_SECRET
          WEBHOOK_URL=$WEBHOOK_URL
          WEB_APP_URL=$WEB_APP_URL
          DEBUG_CHAT_ID=$DEBUG_CHAT_ID
          SELFTEST_CHAT_ID=$SELFTEST_CHAT_ID
          APP_ENV=prod
          APP_DEBUG=false
          ENVEOF"

      - name: Build and restart
        run: |
          ssh -i ~/.ssh/id_rsa -p ${{ vars.SERVER_PORT }} ${{ vars.SERVER_USER }}@${{ vars.SERVER_HOST }} "
            cd /home/pkirillw/dockered-services/max-bot-test && \
            docker compose up -d --build && \
            docker image prune -f"

      - name: Subscribe webhook in MAX
        env:
          WEBHOOK_URL: ${{ vars.WEBHOOK_URL }}
        run: |
          if [ -z "$WEBHOOK_URL" ] || echo "$WEBHOOK_URL" | grep -q 'your-tunnel-host'; then
            echo "WEBHOOK_URL not set, skipping subscription"
            exit 0
          fi
          ssh -i ~/.ssh/id_rsa -p ${{ vars.SERVER_PORT }} ${{ vars.SERVER_USER }}@${{ vars.SERVER_HOST }} "
            cd /home/pkirillw/dockered-services/max-bot-test && \
            docker compose exec -T app bin/console webhook:subscribe --prune"

      - name: Health check
        run: |
          ssh -i ~/.ssh/id_rsa -p ${{ vars.SERVER_PORT }} ${{ vars.SERVER_USER }}@${{ vars.SERVER_HOST }} "
            sleep 5 && cd /home/pkirillw/dockered-services/max-bot-test && docker compose ps"
