name: Test
on:
  push:
    branches: [main, develop]
  pull_request:

jobs:
  test:
    runs-on: macos-arm64
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      
      - name: Create necessary directories
        run: mkdir -p data/users data/cache
      
      - name: Setup Rust
        run: |
          curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
          source $HOME/.cargo/env
      
      - name: Cache cargo
        uses: actions/cache@v3
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: |
            ${{ runner.os }}-cargo-
      
      - name: Install SwitchAudioSource
        continue-on-error: true
        run: brew install switchaudio-source
      
      - name: Run tests
        run: |
          source $HOME/.cargo/env
          cargo test --all
      
      - name: Run clippy
        run: |
          source $HOME/.cargo/env
          cargo clippy --all-targets --all-features -- -D warnings
      
      - name: Check formatting
        run: |
          source $HOME/.cargo/env
          cargo fmt -- --check
      
      - name: Clean test databases
        run: rm -f data/users/test_*.sqlite

  build:
    runs-on: macos-arm64
    needs: test
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      
      - name: Setup Rust
        run: |
          curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
          source $HOME/.cargo/env
      
      - name: Cache cargo
        uses: actions/cache@v3
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
      
      - name: Build release
        run: |
          source $HOME/.cargo/env
          cargo build --release
      
      - name: Upload artifact
        uses: actions/upload-artifact@v3
        with:
          name: markbase-binary
          path: target/release/markbase