# Stage 1: Build & install production dependencies
FROM node:20-alpine AS dependencies

WORKDIR /app

COPY package*.json ./

# Configure Liara npm mirror registry
RUN npm config set registry https://package-mirror.liara.ir/repository/npm/ --global

RUN npm ci --omit=dev --ignore-scripts && npm cache clean --force

# Stage 2: Production runner
FROM node:20-alpine AS runner

WORKDIR /app

ENV NODE_ENV=production
ENV PORT=3000

# Install dumb-init for robust signal handling (PID 1)
RUN apk add --no-cache dumb-init && mkdir -p /app/uploads && chown -R node:node /app

# Switch to non-root user
USER node

# Copy production node_modules with ownership
COPY --chown=node:node --from=dependencies /app/node_modules ./node_modules

# Copy application source code with ownership
COPY --chown=node:node . .

# Expose backend port
EXPOSE 3000

# Run container with dumb-init
ENTRYPOINT ["/usr/bin/dumb-init", "--"]
CMD ["node", "app.js"]
