# Use the official Node.js 18 image
FROM node:18-alpine AS base

# Install dependencies only when needed
FROM base AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat wget
WORKDIR /app
RUN $(pwd)
# Install dependencies based on the preferred package manager
COPY ./package.json ./package-lock.json* /app/
RUN npm ci --omit=dev --legacy-peer-deps

# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules /app/node_modules
#COPY ../../../../package.json ./package-lock.json* /app/
# Install all dependencies (including devDependencies) for building
RUN npm ci --legacy-peer-deps
COPY . .

# Environment variables for build process
ENV NEXT_TELEMETRY_DISABLED 1

# Set dummy environment variables for build (will be overridden at runtime)
ENV DATABASE_URL=postgresql://dummy:dummy@dummy:5432/dummy
ENV BETTER_AUTH_SECRET=dummy-secret-for-build-only-minimum-32-chars
ENV BETTER_AUTH_URL=http://localhost:3000
ENV BETTER_AUTH_EMAIL=build@example.com
ENV NEXT_PUBLIC_APP_URL=http://localhost:3000

# Build the application
RUN npm run build

# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app

ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1

# Install wget for health checks
RUN apk add --no-cache wget

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

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

# Set the correct permission for prerender cache
RUN mkdir -p .next && chown nextjs:nodejs .next
COPY ./common/wait-for-it.sh /usr/bin/wait-for-it
RUN chmod +x /usr/bin/wait-for-it
USER nextjs

EXPOSE 3000

ENV PORT 3000
ENV HOSTNAME "0.0.0.0"

# server.js is created by next build from the standalone output
# https://nextjs.org/docs/pages/api-reference/next-config-js/output
CMD ["node", "server.js"]
