name: Build

on:
  push:
    branches:
      - master
      - main
      - codex/production-intelligence-terminal
  pull_request:
  workflow_dispatch:

jobs:
  test-and-image:
    runs-on: ubuntu-latest
    env:
      REGISTRY_HOST: git.wilkensxl.de
      REGISTRY_USERNAME: MrSphay
      REGISTRY_NAMESPACE: mrsphay
      IMAGE_NAME: intelligence-terminal
      REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4

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

      - name: Install dependencies
        run: npm ci

      - name: Unit tests
        run: npm run test:unit

      - name: Compose config
        run: docker compose config

      - name: Build Docker image
        shell: bash
        run: |
          image="${REGISTRY_HOST}/${REGISTRY_NAMESPACE}/${IMAGE_NAME}"
          build_tag="build-${GITHUB_RUN_ID:-local}-${GITHUB_RUN_NUMBER:-0}"
          echo "BUILD_IMAGE=${image}:${build_tag}" >> "$GITHUB_ENV"
          docker build -t "${image}:${build_tag}" .

      - name: Publish Docker image
        if: ${{ env.REGISTRY_TOKEN != '' }}
        shell: bash
        run: |
          image="${REGISTRY_HOST}/${REGISTRY_NAMESPACE}/${IMAGE_NAME}"
          date_tag="$(date -u +%Y%m%d)"
          echo "${REGISTRY_TOKEN}" | docker login "${REGISTRY_HOST}" -u "${REGISTRY_USERNAME}" --password-stdin
          docker tag "${BUILD_IMAGE}" "${image}:${GITHUB_SHA}"
          docker tag "${BUILD_IMAGE}" "${image}:latest"
          docker tag "${BUILD_IMAGE}" "${image}:${date_tag}"
          docker push "${image}:${GITHUB_SHA}"
          docker push "${image}:latest"
          docker push "${image}:${date_tag}"
