on:
  push:
    branches:
      - master

permissions:
  contents: write
  issues: read

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: checkout
        uses: actions/checkout@v4

      - name: cache dependencies
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/
            ~/.cargo/bin/
            ~/.cache/trunk/
            target/
            node_modules/
          key: ${{ runner.os }}-cargo-${{ hashFiles('./Cargo.lock') }}
          restore-keys: ${{ runner.os }}-cargo-wordl

      - name: install rust
        uses: actions-rs/toolchain@v1
        with:
          profile: minimal
          toolchain: stable
          
      - name: add rust target wasm32-unknown-unknown
        run: rustup target add wasm32-unknown-unknown
      
      - name: install trunk
        run: cargo install trunk

      - name: install node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: install tailwindcss
        run: npm install -g tailwindcss

      - name: list frontend dir (pre build) [DEBUG]
        run: ls -la ./frontend/dist

      - name: build frontend
        working-directory: ./frontend/
        run: |
          trunk build --release

      - name: list frontend dir (pre upload) [DEBUG]
        run: ls -la ./frontend/dist

      - name: upload frontend artifacts
        uses: actions/upload-artifact@v4
        with:
          name: frontend-artifacts
          path: ./frontend/dist

      - name: run tests
        run: |
          cargo test --verbose

  deploy:
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: checkout
        uses: actions/checkout@v4

      - name: remove ./frontend/dist dir
        run: |
          rm -rf ./frontend/dist

      - name: download frontend artifacts
        uses: actions/download-artifact@v4
        with:
          name: frontend-artifacts
          path: ./frontend/dist

      - name: List downloaded artifacts
        run: ls -la ./frontend/dist

      - uses: shuttle-hq/deploy-action@main
        with:
          allow-dirty: "true"
          deploy-key: ${{ secrets.SHUTTLE_API_KEY }}
          working-directory: .
