FROM docker.arvancloud.ir/library/node:22-alpine AS builder

RUN apk add --no-cache openssl

WORKDIR /app

# Copy package files
COPY package*.json ./

# Set NPM registry mirror
RUN npm config set registry https://registry.npmmirror.com
RUN npm config set fetch-retries 10
RUN npm config set fetch-retry-mintimeout 20000
RUN npm config set fetch-retry-maxtimeout 120000

# Install all dependencies (including devDependencies)
RUN for i in 1 2 3 4 5; do npm ci && exit 0 || (echo "Retry $i in 10s..." && sleep 10); done; exit 1

# Copy the rest of the application
COPY . .

# Build the application (compiles TypeScript to dist folder)
# We also generate prisma client here if prisma schema is present.
RUN npx prisma generate
RUN npm run build

# Production image
FROM docker.arvancloud.ir/library/node:22-alpine

RUN apk add --no-cache openssl

WORKDIR /app

# Copy only package files
COPY package*.json ./

# Set NPM registry mirror
RUN npm config set registry https://registry.npmmirror.com
RUN npm config set fetch-retries 10
RUN npm config set fetch-retry-mintimeout 20000
RUN npm config set fetch-retry-maxtimeout 120000

# Install only production dependencies
RUN for i in 1 2 3 4 5; do npm ci --only=production && exit 0 || (echo "Retry $i in 10s..." && sleep 10); done; exit 1

# Copy built artifacts from the builder stage
COPY --from=builder /app/dist ./dist
# Copy generated prisma client:
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=builder /app/node_modules/@prisma/client ./node_modules/@prisma/client

EXPOSE 3000

USER node

# Start the application
CMD ["node", "dist/main"]
