name: Elixir CI

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main
env:
  OTP_VERSION: <%= @erlang_version %>
  ELIXIR_VERSION: <%= @elixir_version %>

concurrency:
  group: ${{ github.workflow }}-${{ github.ref_name }}
  cancel-in-progress: true

jobs:
  mix:
    runs-on: ubuntu-latest
    steps:
      - name: Setup
        uses: byzanteam/jet-actions/setup-elixir@main
        with:
          otp-version: ${{ env.OTP_VERSION }}
          elixir-version: ${{ env.ELIXIR_VERSION }}

      - name: Install Dependencies
        run: mix do deps.get, deps.clean --unused

  build:
    runs-on: ubuntu-latest
    needs: mix
    steps:
      - name: Setup
        uses: byzanteam/jet-actions/setup-elixir@main
        with:
          otp-version: ${{ env.OTP_VERSION }}
          elixir-version: ${{ env.ELIXIR_VERSION }}

      - name: Check formatting
        run: mix format --check-formatted
      - name: Check warnings
        run: mix compile --warnings-as-errors

  test:
    runs-on: ubuntu-latest
    needs: mix
<%= if @database do %>
    services:
      postgres:
        image: postgres:14-alpine
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: <%= @database %>
        ports:
          - 5432:5432
        # Set health checks to wait until postgres has started
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
<% end %>
    steps:
      - name: Setup
        uses: byzanteam/jet-actions/setup-elixir@main
        with:
          otp-version: ${{ env.OTP_VERSION }}
          elixir-version: ${{ env.ELIXIR_VERSION }}
<%= if @database do %>
      - run: mix do ecto.create, ecto.migrate
        env:
          MIX_ENV: test
<% end %>

      - name: Test
        run: mix test

  credo:
    runs-on: ubuntu-latest
    needs: mix
    steps:
      - name: Setup
        uses: byzanteam/jet-actions/setup-elixir@main
        with:
          otp-version: ${{ env.OTP_VERSION }}
          elixir-version: ${{ env.ELIXIR_VERSION }}

      - name: Credo
        run: mix credo --strict

  dialyzer:
    runs-on: ubuntu-latest
    needs: mix
    steps:
      - name: Setup
        uses: byzanteam/jet-actions/setup-elixir@main
        with:
          otp-version: ${{ env.OTP_VERSION }}
          elixir-version: ${{ env.ELIXIR_VERSION }}

      - uses: actions/cache@v3
        with:
          path: priv/plts
          key: ${{ runner.os }}-plt-${{ hashFiles('.tool-versions') }}-${{ hashFiles('**/mix.lock') }}
          restore-keys: |
            ${{ runner.os }}-plt-${{ hashFiles('.tool-versions') }}-

      - name: Dialyzer
        run: mix dialyzer --format github
