stages:
  - frontend_build
  - dockerize

cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - node_modules/
    - .next/cache/

variables:
  NEXT_PUBLIC_ENV: "production"
  OUTPUT_DIR: ".next"
  PROJECT_NAME: $CI_PROJECT_NAME
  DOCKER_IMAGE: "registry.boomlab.party/rheinsw/$CI_PROJECT_NAME"

# Reusable block for docker build & push
.dockerize_script: &dockerize_script
  - |
    RAW_TAG="$CI_COMMIT_REF_NAME"
    TAG="${RAW_TAG//\//_}"  # replace "/" with "_"
    echo "Sanitized tag: $TAG"
    docker build -t $DOCKER_IMAGE:$TAG -f Dockerfile .

    if [[ "$RAW_TAG" == "dev" || "$RAW_TAG" == "production" ]]; then
      echo "Pushing Docker image $DOCKER_IMAGE:$TAG"
      docker push $DOCKER_IMAGE:$TAG
    else
      echo "Skipping Docker push for non-dev or production branch: $RAW_TAG"
    fi

frontend_build_job:
  stage: frontend_build
  image: node:22@sha256:f6b9c31ace05502dd98ef777aaa20464362435dcc5e312b0e213121dcf7d8b95
  script:
    - cd frontend
    - npm install
    - npx next build
    - npm run lint

dockerize_frontend:
  stage: dockerize
  image: docker:20.10@sha256:2967f0819c84dd589ed0a023b9d25dcfe7a3c123d5bf784ffbb77edf55335f0c
  before_script:
    - echo "$CI_REGISTRY_PASSWORD" | docker login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" --password-stdin
  script:
    - cd frontend
    - *dockerize_script
  needs:
    - job: frontend_build_job
