# 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
FROM base AS deps
WORKDIR /temp-deps
COPY package*.json ./
RUN npm ci --ignore-scripts --no-fund --no-audit

# Stage 3: Build
FROM base AS builder
WORKDIR /build
COPY . ./
COPY --from=deps /temp-deps/node_modules ./node_modules
RUN if [ -f package.json ] && grep -q '"build":' package.json; then npm run build; fi

# Stage 4: Runner
FROM base AS runner
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
WORKDIR /app

COPY . ./
COPY --from=builder --chown=appuser:appgroup /build/ ./
RUN chown -R appuser:appgroup /app

USER appuser
ENV NODE_ENV=production
EXPOSE 4000

CMD ["npm", "start"]
