FROM docker.arvancloud.ir/library/node:20-slim AS base
ENV NEXT_TELEMETRY_DISABLED=1
ENV COREPACK_NPM_REGISTRY=https://package-mirror.liara.ir/repository/npm/
ENV NEXT_SWC_DOWNLOAD_DISABLED=1
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=1
ENV PRISMA_ENGINES_CHECKSUM_IGNORE_MISSING=1
WORKDIR /app

RUN corepack enable && corepack prepare pnpm@9 --activate

# ── deps ──────────────────────────────────────────────────────────────────────
FROM base AS deps
COPY package.json pnpm-lock.yaml* ./
RUN pnpm config set registry https://package-mirror.liara.ir/repository/npm/ && \
    pnpm install --frozen-lockfile --network-concurrency 1

# ── builder ───────────────────────────────────────────────────────────────────
FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Pre-downloaded Prisma engines for node:20-slim (debian-openssl-3.0.x)
ENV PRISMA_QUERY_ENGINE_LIBRARY=/app/prisma-binaries/libquery_engine-debian-openssl-3.0.x.so.node
ENV PRISMA_SCHEMA_ENGINE_BINARY=/app/prisma-binaries/schema-engine-debian-openssl-3.0.x

RUN ./node_modules/.bin/prisma generate
# Placeholder only — real DATABASE_URL is injected at runtime via docker-compose
ENV DATABASE_URL="mysql://build:build@localhost:3306/build"
RUN ./node_modules/.bin/next build && ./node_modules/.bin/next-sitemap

# ── runner ────────────────────────────────────────────────────────────────────
FROM docker.arvancloud.ir/library/node:20-slim AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
ENV NEXT_TELEMETRY_DISABLED=1
ENV PRISMA_ENGINES_CHECKSUM_IGNORE_MISSING=1

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

# Prisma client needs the query engine at runtime
COPY --from=builder /app/prisma-binaries ./prisma-binaries
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=builder /app/node_modules/@prisma/client ./node_modules/@prisma/client

ENV PRISMA_QUERY_ENGINE_LIBRARY=/app/prisma-binaries/libquery_engine-debian-openssl-3.0.x.so.node

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

RUN mkdir -p /app/public/uploads && chown nextjs:nodejs /app/public/uploads

USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]
