name: backend-tests

on:
  pull_request:
    paths:
      - 'backend/**'
      - 'Dockerfile'
      - 'Makefile'
      - 'scripts/coverage-gate.sh'
      - '.github/workflows/test.yml'
  push:
    branches: [main]

jobs:
  unit:
    name: Unit tests + coverage gate
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.25'
          cache: true
          cache-dependency-path: backend/go.sum

      - name: Generate swagger docs
        run: |
          go install github.com/swaggo/swag/cmd/swag@latest
          cd backend && swag init

      - name: Run unit tests with race detector and coverage
        run: |
          cd backend
          go test -race -coverprofile=../coverage.out -coverpkg=./... ./...

      - name: Enforce coverage gate
        run: bash scripts/coverage-gate.sh coverage.out

      - name: Upload coverage artifact
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: coverage
          path: coverage.out

      - name: Upload coverage reports to Codecov
        uses: codecov/codecov-action@v5
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
          slug: Noooste/garage-ui
          files: ./coverage.out
          fail_ci_if_error: false

  smoke:
    name: Smoke test (docker compose)
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.25'
          cache: true
          cache-dependency-path: backend/go.sum

      - name: Run smoke test
        run: make test-smoke

      - name: Dump compose logs on failure
        if: failure()
        run: |
          docker compose -p garage-ui-smoke \
            -f backend/tests/smoke/docker-compose.test.yml logs --no-color || true

      - name: Tear down compose
        if: always()
        run: |
          docker compose -p garage-ui-smoke \
            -f backend/tests/smoke/docker-compose.test.yml down -v || true

