# syntax=docker/dockerfile:1.7
# TaskStream images (one Dockerfile, two targets):
#   docker compose up -d --build         → api + web + infrastructure
#
# @pi/ui comes from Pireon's private Nexus. Its token is passed as a build
# secret (compose: `secrets.npmrc` → ~/.npmrc) and never lands in a layer.

# ---- Workspace dependencies (shared by both builds) --------------------
FROM node:22-alpine AS deps
WORKDIR /workspace
ENV NX_DAEMON=false NX_NO_CLOUD=true NX_SKIP_NX_CACHE=true
COPY package.json package-lock.json .npmrc ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci --no-audit --no-fund

# ---- API: Nest bundle + pruned package.json / lockfile -----------------
FROM deps AS build-api
COPY . .
RUN npx nx run api:prune

FROM node:22-alpine AS api
WORKDIR /app
ENV NODE_ENV=production PORT=3000
# Only the API's runtime dependencies (apps/api/package.json): no frontend
# packages, nothing from the private registry.
COPY --from=build-api /workspace/dist/apps/api/package.json /workspace/dist/apps/api/package-lock.json ./
RUN npm ci --omit=dev --ignore-scripts --no-audit --no-fund && npm cache clean --force
COPY --from=build-api /workspace/dist/apps/api/main.js ./
USER node
EXPOSE 3000
HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=5 \
  CMD wget -qO- http://127.0.0.1:3000/api/health > /dev/null || exit 1
CMD ["node", "main.js"]

# ---- Web: Angular SPA behind nginx (proxies /api and /graphql) ---------
FROM deps AS build-web
COPY . .
RUN npx nx build web --configuration=production

FROM nginx:1.27-alpine AS web
COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build-web /workspace/dist/apps/web/browser /usr/share/nginx/html
EXPOSE 80
HEALTHCHECK --interval=10s --timeout=3s --retries=5 CMD wget -qO- http://127.0.0.1/ > /dev/null || exit 1
