FROM docker.iranserver.com/node:20-bookworm-slim AS base

ENV NEXT_TELEMETRY_DISABLED=1

RUN rm -f /etc/apt/sources.list /etc/apt/sources.list.d/* && \
    printf '%s\n' \
    'deb https://mirror-linux.runflare.com/debian/ bookworm main contrib non-free non-free-firmware' \
    'deb https://mirror-linux.runflare.com/debian/ bookworm-updates main contrib non-free non-free-firmware' \
    'deb https://mirror-linux.runflare.com/debian-security/ bookworm-security main contrib non-free non-free-firmware' \
    '' \
    'deb [trusted=yes] https://mirror2.chabokan.net/debian bookworm main contrib non-free non-free-firmware' \
    'deb [trusted=yes] https://mirror2.chabokan.net/debian-security bookworm-security main contrib non-free non-free-firmware' \
    '' \
    'deb http://mirror.iranserver.com/debian/ bookworm main contrib non-free non-free-firmware' \
    'deb-src http://mirror.iranserver.com/debian/ bookworm main contrib non-free non-free-firmware' \
    > /etc/apt/sources.list

RUN npm config set registry https://package-mirror.liara.ir/repository/npm/ && \
    npm config set @chabokan:registry https://mirror2.chabokan.net/npm/ && \
    npm config set strict-ssl false && \
    npm config set fetch-retries 5 && \
    npm config set fetch-retry-mintimeout 20000

# ---- deps stage ----
FROM base AS deps
WORKDIR /app

COPY package.json package-lock.json ./

RUN npm ci --ignore-scripts

# ---- build stage ----
FROM base AS builder
WORKDIR /app

COPY --from=deps /app/node_modules ./node_modules
COPY . .

ENV NODE_ENV=production

RUN npm run build

# ---- production stage ----
FROM base AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV PORT=9031
ENV HOSTNAME=0.0.0.0

RUN addgroup --system --gid 1001 nodejs && \
    adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 9031

CMD ["node", "server.js"]
