name: CI

on:
  pull_request:
  push:
    branches:
      - main
    tags:
      - 'v*'

env:
  REGISTRY: gitea.reversed.dev
  IMAGE_NAME: space/evil-wordle

jobs:
  test:
    name: Lint and build app
    runs-on: ubuntu-latest

    steps:
      - name: Check out repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Lint
        run: npm run lint

      - name: Build app
        run: npm run build

      - name: Install Docker if missing
        run: |
          if ! command -v docker >/dev/null 2>&1; then
            curl -fsSL https://get.docker.com | sh
          fi
          docker --version
          docker compose version

      - name: Validate compose file
        run: docker compose config

  publish-image:
    name: Publish container image
    runs-on: ubuntu-latest
    needs: test
    if: ${{ github.event_name == 'push' }}

    steps:
      - name: Check out repository
        uses: actions/checkout@v4

      - name: Install and start Docker if missing
        run: |
          if ! command -v docker >/dev/null 2>&1; then
            curl -fsSL https://get.docker.com | sh
          fi

          if ! docker info >/dev/null 2>&1; then
            if command -v service >/dev/null 2>&1; then
              service docker start || true
            fi

            if ! docker info >/dev/null 2>&1; then
              nohup dockerd >/tmp/dockerd.log 2>&1 &
            fi

            timeout 60 sh -c 'until docker info >/dev/null 2>&1; do sleep 2; done'
          fi

          docker --version
          docker compose version

      - name: Log in to Gitea registry
        run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login "$REGISTRY" -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin

      - name: Build image
        run: |
          SHORT_SHA="${GITHUB_SHA::12}"
          docker build \
            --tag "$REGISTRY/$IMAGE_NAME:latest" \
            --tag "$REGISTRY/$IMAGE_NAME:$SHORT_SHA" \
            .

      - name: Push image
        run: |
          SHORT_SHA="${GITHUB_SHA::12}"
          docker push "$REGISTRY/$IMAGE_NAME:latest"
          docker push "$REGISTRY/$IMAGE_NAME:$SHORT_SHA"
