.build-next-template:
  stage: build
  image: node:22@sha256:f6b9c31ace05502dd98ef777aaa20464362435dcc5e312b0e213121dcf7d8b95
  script:
    - |
      cd $WORKDIR_PATH
      npm ci
      npm run build
  artifacts:
    expire_in: 3 days
    paths:
      - $WORKDIR_PATH/.next
      - $WORKDIR_PATH/public
      - $WORKDIR_PATH/package.json
      - $WORKDIR_PATH/package-lock.json

.docker-login:
  before_script:
    - echo "$CI_REGISTRY_PASSWORD" | docker login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" --password-stdin

.docker-build-template:
  image: docker:20.10@sha256:2967f0819c84dd589ed0a023b9d25dcfe7a3c123d5bf784ffbb77edf55335f0c
  extends: .docker-login
  script:
    - docker build --build-arg WORKDIR_PATH=$WORKDIR_PATH -t $CI_REGISTRY_IMAGE/$IMAGE_NAME:$CI_COMMIT_REF_SLUG -f $DOCKERFILE_PATH .
    - docker push $CI_REGISTRY_IMAGE/$IMAGE_NAME:$CI_COMMIT_REF_SLUG

# Deployment
.install-deploy-key: &install-deploy-key
  - |
    echo "Installing SSH deploy key..."
    which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )
    mkdir -p ~/.ssh
    echo "$DEPLOY_KEY_BASE64" | base64 -d > ~/.ssh/deploy_key
    chmod 600 ~/.ssh/deploy_key
    eval "$(ssh-agent -s)"
    ssh-add ~/.ssh/deploy_key
    if [[ "$TAG" == "dev" || "$TAG" == "pipeline" ]]; then
      HOST="$DEPLOY_DEV_HOST"
      PORT="${DEPLOY_DEV_PORT:-22}"
    else
      HOST="$DEPLOY_PROD_HOST"
      PORT="${DEPLOY_PROD_PORT:-22}"
    fi
    echo "Scanning SSH host $HOST on port $PORT"
    ssh-keyscan -p "$PORT" "$HOST" >> ~/.ssh/known_hosts || true

.deploy-template:
  stage: deploy
  image: docker:20.10@sha256:2967f0819c84dd589ed0a023b9d25dcfe7a3c123d5bf784ffbb77edf55335f0c
  before_script:
    - !reference [ .install-deploy-key ]
  script: |
    if [[ "$TAG" == "dev" || "$TAG" == "pipeline" ]]; then
      HOST="$DEPLOY_DEV_HOST"
      PORT="${DEPLOY_DEV_PORT:-22}"
    else
      HOST="$DEPLOY_PROD_HOST"
      PORT="${DEPLOY_PROD_PORT:-22}"
    fi
    
    # Append :$TAG to all matching GitLab image references
    sed -i -E "s|(image:\s+registry\.boomlab\.party/[a-zA-Z0-9._/-]+)(\s*)|\1:$TAG\2|g" docker-compose.yml

    echo "Copying docker-compose.yml to $HOST:$REMOTE_ENV_PATH/docker-compose.yml"
    # Ensure remote path exists before scp
    ssh -p "$PORT" "$DEPLOY_USER@$HOST" "mkdir -p $REMOTE_ENV_PATH"
    scp -P "$PORT" docker-compose.yml "$DEPLOY_USER@$HOST:$REMOTE_ENV_PATH/docker-compose.yml"
    scp -P "$PORT" nginx.conf "$DEPLOY_USER@$HOST:$REMOTE_ENV_PATH/nginx.conf"
    scp -P "$PORT" auth.lua "$DEPLOY_USER@$HOST:$REMOTE_ENV_PATH/auth.lua"
    
    echo "Deploying DEMO on $HOST"
    ssh -p "$PORT" "$DEPLOY_USER@$HOST" "
      cd $REMOTE_ENV_PATH
      echo "$CI_REGISTRY_PASSWORD" | docker login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" --password-stdin  
      docker compose down || true
      docker compose pull || true
      docker compose up -d
    "
    
