###############
### STAGE 1: Build app
###############
ARG BUILDER_IMAGE=node:24-alpine3.22
ARG NGINX_IMAGE=nginx:1.29-alpine3.22-slim

FROM $BUILDER_IMAGE AS builder
ARG NPM_REGISTRY_URL=https://registry.npmjs.org/
ARG BUILD_ENVIRONMENT_OPTIONS="--configuration production"
ARG PUPPETEER_DOWNLOAD_HOST_ARG=https://storage.googleapis.com
ARG PUPPETEER_CHROMIUM_REVISION_ARG=1011831
# Build ko Chromium nahi chahiye — skip (warna npm ci Chromium download par atak jata hai).
ARG PUPPETEER_SKIP_DOWNLOAD_ARG=true

# Set the environment variable to increase Node.js memory limit
# (Mifos web-app ka production build memory-heavy hai; upstream build:prod
#  16384 use karta hai. 4096 par 'ng build' OOM ho jata hai.)
ENV NODE_OPTIONS="--max-old-space-size=8192"

RUN apk add --no-cache git

WORKDIR /usr/src/app

ENV PATH=/usr/src/app/node_modules/.bin:$PATH

# Export Puppeteer env variables for installation with non-default registry.
ENV PUPPETEER_DOWNLOAD_HOST=$PUPPETEER_DOWNLOAD_HOST_ARG
ENV PUPPETEER_CHROMIUM_REVISION=$PUPPETEER_CHROMIUM_REVISION_ARG
ENV PUPPETEER_SKIP_DOWNLOAD=$PUPPETEER_SKIP_DOWNLOAD_ARG

# Test/e2e tooling ke bhaari binary downloads skip karo — build inhe use nahi
# karta, aur inke bina npm ci turant complete ho jata hai.
#   Cypress   -> ~250MB binary (CI me sabse zyada atakta hai)
#   Playwright-> browser binaries
ENV CYPRESS_INSTALL_BINARY=0
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1

COPY ./ /usr/src/app/

RUN npm cache clear --force

RUN npm config set fetch-retry-maxtimeout 120000
RUN npm config set registry $NPM_REGISTRY_URL --location=global

RUN npm ci

RUN sh -c "ng build --output-path=/dist $BUILD_ENVIRONMENT_OPTIONS"

###############
### STAGE 2: Serve app with nginx ###
###############
FROM $NGINX_IMAGE

# envsubst (gettext) alpine-slim me nahi hota — runtime env.js generation ke
# liye zaroori hai, isliye explicitly install kar rahe hain.
RUN apk add --no-cache gettext

# Static-only nginx config (SPA fallback, no API proxy). Stock default.conf
# ko replace karta hai taaki deep-link refresh par 404 na aaye.
COPY nginx.spa.conf /etc/nginx/conf.d/default.conf

COPY --from=builder /dist/browser /usr/share/nginx/html

EXPOSE 80

# When the container starts, replace the env.js with values from environment variables
CMD ["/bin/sh",  "-c",  "envsubst < /usr/share/nginx/html/assets/env.template.js > /usr/share/nginx/html/assets/env.js && exec nginx -g 'daemon off;'"]
