name: iOS Build & Detox

on:
  workflow_call:
    inputs:
      NVMRC:
        required: true
        type: string
      MAP_IMPL:
        description: "The map implementation to use (mapbox,maplibre or mapbox-gl)"
        default: mapbox
        required: false
        type: string
    secrets:
      MAPBOX_ACCESS_TOKEN:
        required: true
      MAPBOX_DOWNLOAD_TOKEN:
        required: true

jobs:
  build:
    runs-on: macos-12
    timeout-minutes: 55

    defaults:
      run:
        working-directory: ./example

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Access Token
        run: echo $MAPBOX_ACCESS_TOKEN > ./accesstoken
        env:
          MAPBOX_ACCESS_TOKEN: ${{ secrets.MAPBOX_ACCESS_TOKEN }}

      - name: Setup .netrc with MAPBOX_DOWNLOAD_TOKEN
        run: |
          echo 'machine api.mapbox.com' >> ~/.netrc
          echo 'login mapbox' >> ~/.netrc
          echo "password $MAPBOX_DOWNLOAD_TOKEN" >> ~/.netrc
          chmod 0600 ~/.netrc
        env:
          MAPBOX_DOWNLOAD_TOKEN: ${{ secrets.MAPBOX_DOWNLOAD_TOKEN }}

      - name: Setup node ${{ inputs.NVMRC }}
        uses: actions/setup-node@v2.5.0
        with:
          node-version: ${{ inputs.NVMRC }}

      - name: Install Yarn Dependencies
        run: yarn install --network-timeout 1000000

      - name: Install Pod Dependencies
        run: cd ios && pod --version && pod install
        env:
          CI_MAP_IMPL: ${{ inputs.MAP_IMPL }}

      - name: Install Detox Dependencies
        run: |
          brew tap wix/brew
          brew install applesimutils
          brew install xcbeautify

      - name: Build for detox
        run: yarn detox build --configuration ios.debug | xcbeautify -qq

      - name: Test with detox
        run: |
          npx detox --version
          yarn detox test --configuration ios.debug --debug-synchronization 500 --loglevel trace --record-logs all --take-screenshots all
        env:
          SKIP_TESTS_NO_METAL: ${{ inputs.MAP_IMPL == 'mapbox' }}

      - name: Store Detox artifacts on test failure
        uses: actions/upload-artifact@v3
        if: failure()
        with:
          name: detox-artifacts
          path: example/artifacts
