FROM node:24-slim AS base

ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"

RUN corepack enable

WORKDIR /app



FROM base AS prod-deps

# pnpm-workspace.yaml carries onlyBuiltDependencies; without it pnpm blocks the postinstall
# scripts it lists, so the install here would not match a local one.
COPY pnpm-lock.yaml pnpm-workspace.yaml ./

RUN --mount=type=cache,target=/pnpm/store \
    pnpm fetch --frozen-lockfile

COPY package.json ./

RUN --mount=type=cache,target=/pnpm/store \
    pnpm install --frozen-lockfile --prod --offline



FROM base AS build

COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./

RUN --mount=type=cache,target=/pnpm/store \
    pnpm install --frozen-lockfile

COPY . .

RUN pnpm run build



FROM node:24-slim

# Setup a non-root user
RUN groupadd -g 9999 appuser && \
    useradd -u 9999 -g appuser -m -d /app -s /sbin/nologin appuser
    
COPY --from=prod-deps --chown=appuser:appuser /app/node_modules /app/node_modules
COPY --from=build --chown=appuser:appuser /app/build /app/build

USER appuser

ENV ORIGIN=http://localhost:3000
ENV BODY_SIZE_LIMIT=2G

EXPOSE 3000

WORKDIR /app

HEALTHCHECK --interval=10s --timeout=3s --retries=5 --start-period=10s \
  CMD ["node", "-e", "fetch(`http://127.0.0.1:${process.env.PORT || 3000}/login`).then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]

CMD [ "node", "build" ]
