# Stage 1: Base — shared tooling and system config
FROM node:22-alpine AS base

ENV TZ=Asia/Tehran

# Runflare build hosts cannot reach registry.npmjs.org; use their npm mirror.
RUN npm install -g pnpm@9.15.9 --registry=https://mirror-npm.runflare.com

# Stage 2: Install all dependencies (including dev)
FROM base AS deps
WORKDIR /temp-deps
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile --loglevel info \
    --registry=https://mirror-npm.runflare.com

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

# Stage 4: Production deps only
FROM base AS prod-deps
WORKDIR /temp-deps
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --prod --frozen-lockfile --loglevel info \
    --registry=https://mirror-npm.runflare.com

# Stage 5: Runner
FROM base AS runner

RUN addgroup -S appgroup && adduser -S appuser -G appgroup

WORKDIR /app

# Copy only production node_modules and build output
COPY --from=prod-deps --chown=appuser:appgroup /temp-deps/node_modules ./node_modules
COPY --from=builder --chown=appuser:appgroup /build/dist ./dist
COPY --chown=appuser:appgroup package.json ./

RUN chown -R appuser:appgroup /app

USER appuser

ENV NODE_ENV=production
EXPOSE 3500

CMD ["pnpm", "start"]
