FROM node:20-alpine AS deps
WORKDIR /app

RUN npm config set registry https://mirror-npm.runflare.com/ \
  && npm config set replace-registry-host always

ENV PRISMA_SKIP_POSTINSTALL_GENERATE=1

COPY package.json package-lock.json ./
RUN npm ci --ignore-scripts || npm install --ignore-scripts

FROM node:20-alpine AS builder
WORKDIR /app

ARG DATABASE_URL
ARG NEXTAUTH_URL
ENV DATABASE_URL=$DATABASE_URL
ENV NEXTAUTH_URL=$NEXTAUTH_URL
ENV NEXT_TELEMETRY_DISABLED=1
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=1

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

RUN test -f lib/generated/prisma/index.js

ENV NODE_ENV=production
RUN npm run build:docker

FROM node:20-alpine AS runner
WORKDIR /app

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

RUN addgroup -S nextjs \
  && adduser -S nextjs -G nextjs

COPY --from=builder --chown=nextjs:nextjs /app/package.json ./package.json
COPY --from=builder --chown=nextjs:nextjs /app/node_modules ./node_modules
COPY --from=builder --chown=nextjs:nextjs /app/.next ./.next
COPY --from=builder --chown=nextjs:nextjs /app/public ./public
COPY --from=builder --chown=nextjs:nextjs /app/prisma ./prisma
COPY --from=builder --chown=nextjs:nextjs /app/lib/generated ./lib/generated
COPY --from=builder --chown=nextjs:nextjs /app/next.config.* ./

USER nextjs

EXPOSE 3000

CMD ["npm", "run", "start"]
