name: Build & Deploy to Pages

on:
  workflow_dispatch:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

# Allow only one concurrent deployment
concurrency:
  group: "pages"
  cancel-in-progress: false

env:
  APP_FOLDER: "calories-tracker"

jobs:
  build-deploy:
    runs-on: easynode-debian
    env:
      VITE_APPWRITE_PROJECT_ID: ${{ secrets.VITE_APPWRITE_PROJECT_ID }}
      VITE_APPWRITE_ENDPOINT: ${{ secrets.VITE_APPWRITE_ENDPOINT }}
      VITE_APPWRITE_DBID: ${{ secrets.VITE_APPWRITE_DBID }}
      VITE_APPWRITE_FOODENTRIESID: ${{ secrets.VITE_APPWRITE_FOODENTRIESID }}
      VITE_APPWRITE_USERSETTINGSID: ${{ secrets.VITE_APPWRITE_USERSETTINGSID }}
      VITE_APPWRITE_MONTLYCALORIESID: ${{ secrets.VITE_APPWRITE_MONTLYCALORIESID }}
      VITE_APPWRITE_SHAREDDAYSID: ${{ secrets.VITE_APPWRITE_SHAREDDAYSID }}
      VITE_CLAUDE_API_KEY: ${{ secrets.VITE_CLAUDE_API_KEY }}
    
    steps:
    - name: Checkout
      uses: actions/checkout@v4
     
    - name: Cache npm dependencies
      uses: actions/cache@v3
      with:
        path: ~/.npm
        key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
        restore-keys: |
          ${{ runner.os }}-npm
    
    - name: Install dependencies
      run: npm ci
      
    - name: Build
      run: npm run build

    - name: Install rsync + ssh client
      run: apt-get update -qq && apt-get install -y -qq rsync openssh-client

    - name: Configure SSH
      run: |
        mkdir -p ~/.ssh
        echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/deploy_key
        chmod 600 ~/.ssh/deploy_key
        ssh-keyscan -H "${{ secrets.DEPLOY_HOST }}" >> ~/.ssh/known_hosts

    - name: Ensure destination folder exists
      run: |
        ssh -i ~/.ssh/deploy_key deploy@${{ secrets.DEPLOY_HOST }} \
          "mkdir -p /srv/sites/${{ env.APP_FOLDER }} && chmod 755 /srv/sites/${{ env.APP_FOLDER }}"

    - name: Upload site
      run: |
        rsync -avz --delete \
          -e "ssh -i ~/.ssh/deploy_key" \
          ./dist/ deploy@${{ secrets.DEPLOY_HOST }}:/srv/sites/${{ env.APP_FOLDER }}/

