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

# Use Alpine mirror
# RUN sed -i 's|https://dl-cdn.alpinelinux.org/alpine|https://mirror.de.velop.ir/alpine|g' /etc/apk/repositories

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

# Set timezone (Node.js respects TZ env variable natively)
ENV TZ=Asia/Tehran

# Set workdir for clarity
WORKDIR /app

# Stage 2: Dependencies (for build)
FROM base AS deps
WORKDIR /temp-deps
COPY package*.json ./
RUN npm ci --ignore-scripts --no-fund --no-audit

# Stage 3: Production dependencies only
FROM base AS prod-deps
WORKDIR /temp-deps
COPY package*.json ./
RUN npm ci --omit=dev --ignore-scripts --no-fund --no-audit

# 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 --from=builder --chown=appuser:appgroup /build/package*.json ./
COPY --from=prod-deps --chown=appuser:appgroup /temp-deps/node_modules ./node_modules
COPY --from=builder --chown=appuser:appgroup /build/dist ./dist
COPY --from=builder --chown=appuser:appgroup /build/database ./database

USER appuser
ENV NODE_ENV=production
EXPOSE 4000

CMD ["npm", "run", "start:prod"]
