ARG NODE_IMAGE=mirror.soroushasadi.com/node:20-alpine

# ==================== DEPS STAGE ====================
FROM ${NODE_IMAGE} AS deps
WORKDIR /app

COPY web/admin/package*.json ./

ARG NPM_REGISTRY=https://mirror.soroushasadi.com/repository/npm-group/

RUN npm ci --legacy-peer-deps --ignore-scripts \
    --registry ${NPM_REGISTRY} \
    --strict-ssl=false \
    && NEXT_VER=$(node -p "require('./node_modules/next/package.json').version") \
    && ls node_modules/@next/swc-linux-x64-musl 2>/dev/null \
    || npm install --no-save --ignore-scripts \
       --registry ${NPM_REGISTRY} \
       --strict-ssl=false \
       "@next/swc-linux-x64-musl@${NEXT_VER}"


# ==================== BUILDER STAGE ====================
FROM ${NODE_IMAGE} AS builder
WORKDIR /app

ARG NEXT_PUBLIC_ADMIN_API_URL=http://localhost:5081

ENV NEXT_PUBLIC_ADMIN_API_URL=$NEXT_PUBLIC_ADMIN_API_URL
ENV NEXT_TELEMETRY_DISABLED=1

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

RUN npm run build


# ==================== RUNNER STAGE ====================
FROM ${NODE_IMAGE} AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
ENV NEXT_TELEMETRY_DISABLED=1

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 3000
CMD ["node", "server.js"]