name: Node.js CI

on:
  push:
    branches: [ main ]
    tags: 
      - v*
  pull_request:
    branches: [ main ]

jobs:
  build:

    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - name: Use NodeJS
        uses: actions/setup-node@v3
        with:
          scope: '@ozee-io'
          registry-url: 'https://registry.npmjs.org'
      - run: yarn install
      
      - run: yarn test --collectCoverage
      
      # Set up QEMU and Docker Buildx
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v2
      - name: Set up Docker Buildx
        id: buildx
        uses: docker/setup-buildx-action@v2
        with:
          install: true
          platforms: linux/amd64

      # Login to the Github Docker Registry
      - name: Login to Github Docker Registry
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata (tags, labels)
        id: metadata
        uses: docker/metadata-action@v4
        with:
          images: ghcr.io/ozee-io/fga-transformer-cli
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}

      - run: yarn publish
        if: github.event_name == 'push' && contains(github.ref, 'refs/tags/')
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Push
        uses: docker/build-push-action@v3
        if: github.event_name == 'push' && contains(github.ref, 'refs/tags/')
        with:
          push: true
          builder: ${{ steps.buildx.outputs.name }}
          labels: ${{ steps.metadata.outputs.labels }}
          tags: ${{ steps.metadata.outputs.tags }}
