FROM node:20-alpine AS builder

RUN apk add --no-cache cairo-dev pango-dev libjpeg-turbo-dev giflib-dev librsvg-dev pixman-dev python3 make g++

WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .

# Pull Google Fonts into ./fonts/ so they end up in the runtime image. If the
# build host has no network this step will produce missing-variant warnings;
# the build still succeeds and the server falls back to system fonts.
RUN npm run fetch-fonts || echo "Font fetch had warnings; continuing with whatever was downloaded."

RUN npm run build

FROM node:20-alpine

# Cairo + Pango are required by node-canvas at runtime.
# The font packages cover the proprietary template families (Impact, Times,
# Courier, Arial) via free equivalents that fontconfig will alias, plus emoji
# rendering for sticker exports.
RUN apk add --no-cache \
    cairo pango libjpeg-turbo giflib librsvg pixman \
    ttf-liberation ttf-dejavu font-noto font-noto-emoji \
    fontconfig

WORKDIR /app
COPY package*.json ./
RUN npm install --omit=dev

COPY server.js ./
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/fonts ./fonts
RUN mkdir -p /app/uploads /app/exports

# Refresh fontconfig's cache so the newly-copied custom fonts are discoverable.
RUN fc-cache -f /app/fonts || true

HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:3001/api/health || exit 1

EXPOSE 3001
ENV NODE_ENV=production
CMD ["node", "server.js"]
