#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")/.."
source deploy/env.sh

GIT_SHA=$(git rev-parse --short HEAD 2>/dev/null || date +%s)
BASE_TAG=${BUILD_TAG:-$GIT_SHA}

# Optional dev override: set FORCE_DEV_TAG=1 to append a timestamp without committing
if [[ -n "${FORCE_DEV_TAG:-}" ]]; then
  BASE_TAG="${BASE_TAG}-dev$(date +%s)"
fi

IMAGE_REPO="${REGISTRY}/${REGISTRY_REPO}"
IMAGE="${IMAGE_REPO}:${BASE_TAG}"
IMAGE_LATEST="${IMAGE_REPO}:latest"

echo "Building image:"
echo "  $IMAGE"
echo "  $IMAGE_LATEST"

# npm audit (high severity and above)
echo "Running npm audit (high)..."
npm audit --audit-level=high || echo "npm audit reported issues above."

# Build
docker build --build-arg APP_VERSION="$GIT_SHA" -t "$IMAGE" -t "$IMAGE_LATEST" .

echo "$IMAGE" > deploy/.last-image

echo "Done. Last image: $IMAGE"

# Trivy image scan (if available)
if command -v trivy >/dev/null 2>&1; then
  echo "Running Trivy scan on $IMAGE ..."
  trivy image --exit-code 0 "$IMAGE" || true
else
  echo "Trivy not installed; skipping image scan."
fi
