# syntax=docker/dockerfile:1.7
FROM node:22-bookworm-slim

RUN corepack enable

WORKDIR /app

COPY package.json pnpm-lock.yaml pnpm-workspace.yaml /app/
COPY patches /app/patches
COPY packages/types/package.json /app/packages/types/package.json
COPY packages/ui/package.json /app/packages/ui/package.json
COPY ee/packages/utils/package.json /app/ee/packages/utils/package.json
COPY ee/apps/den-web/package.json /app/ee/apps/den-web/package.json

RUN pnpm install --frozen-lockfile --trust-lockfile --filter @openwork-ee/den-web...

COPY packages/types /app/packages/types
COPY packages/ui /app/packages/ui
COPY ee/packages/utils /app/ee/packages/utils
COPY ee/apps/den-web /app/ee/apps/den-web

WORKDIR /app/ee/apps/den-web

# Source-map upload is build-only; runtime Sentry still requires its own backend and DSN configuration.
ARG DEN_WEB_UPLOAD_SENTRY_SOURCEMAPS=0
ARG DEN_WEB_SENTRY_UPLOAD_BUILD_ID=disabled
RUN --mount=type=secret,id=sentry_auth_token,required=false \
  --mount=type=secret,id=sentry_org,required=false \
  --mount=type=secret,id=sentry_project,required=false \
  --mount=type=secret,id=sentry_url,required=false \
  --mount=type=secret,id=sentry_release,required=false \
  --mount=type=secret,id=sentry_dist,required=false \
  set -eu; \
  export DEN_WEB_UPLOAD_SENTRY_SOURCEMAPS; \
  case "$DEN_WEB_UPLOAD_SENTRY_SOURCEMAPS" in \
  1|[Tt][Rr][Uu][Ee]|[Yy][Ee][Ss]|[Oo][Nn]) \
    if [ ! -s /run/secrets/sentry_auth_token ] || [ ! -s /run/secrets/sentry_org ] || [ ! -s /run/secrets/sentry_project ]; then \
      echo "Den Web Sentry source-map upload requested but required BuildKit secrets are incomplete" >&2; \
      exit 1; \
    fi; \
    export SENTRY_AUTH_TOKEN="$(cat /run/secrets/sentry_auth_token)"; \
    export SENTRY_ORG="$(cat /run/secrets/sentry_org)"; \
    export SENTRY_PROJECT="$(cat /run/secrets/sentry_project)"; \
    if [ -s /run/secrets/sentry_url ]; then export SENTRY_URL="$(cat /run/secrets/sentry_url)"; fi; \
    if [ -s /run/secrets/sentry_release ]; then export SENTRY_RELEASE="$(cat /run/secrets/sentry_release)"; fi; \
    if [ -s /run/secrets/sentry_dist ]; then export SENTRY_DIST="$(cat /run/secrets/sentry_dist)"; fi; \
    : "$DEN_WEB_SENTRY_UPLOAD_BUILD_ID"; \
    ;; \
  esac; \
  pnpm run build

EXPOSE 3005

HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD node -e "fetch('http://127.0.0.1:' + (process.env.PORT || '3005') + '/api/health').then((res) => process.exit(res.ok ? 0 : 1)).catch(() => process.exit(1))"

CMD ["sh", "-lc", "/app/ee/apps/den-web/node_modules/.bin/next start --hostname 0.0.0.0 --port ${PORT:-3005}"]
