# Stage 1: Base
FROM node:22-alpine AS base

# Alpine mirror + timezone data
RUN sed -i 's|https://dl-cdn.alpinelinux.org/alpine|https://mirror.de.velop.ir/alpine|g' /etc/apk/repositories \
    && apk add --no-cache tzdata

ENV TZ=Asia/Tehran
# ENV NPM_CONFIG_REGISTRY=https://package-mirror.liara.ir/repository/npm/
# RUN npm config set registry https://package-mirror.liara.ir/repository/npm/

WORKDIR /app

# Stage 2: Build dependencies
FROM base AS deps
WORKDIR /temp-deps
COPY package*.json ./
RUN npm ci  

# Stage 3: Production dependencies (prune dev deps from the already-installed tree)
FROM deps AS prod-deps
RUN npm prune --omit=dev

# Stage 4: Build
FROM base AS builder
WORKDIR /build
COPY package*.json ./
COPY --from=deps /temp-deps/node_modules ./node_modules
COPY . .
RUN npm run build

# Stage 5: Runner
FROM base AS runner
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

WORKDIR /app

COPY package*.json ./
COPY --from=prod-deps --chown=appuser:appgroup /temp-deps/node_modules ./node_modules
COPY --from=builder --chown=appuser:appgroup /build/dist ./dist

USER appuser
ENV NODE_ENV=production
EXPOSE 4000

CMD ["node", "--max-old-space-size=2048", "dist/src/main.js"]
