# thinkera.academy: Next.js + Payload CMS, one container. PostgreSQL runs beside it (docker-compose.yml).
#   docker compose up -d --build
FROM node:22-alpine AS base
RUN apk add --no-cache libc6-compat
WORKDIR /app
# An extra root certificate for machines whose antivirus inspects HTTPS (certs/extra-ca.pem; empty = none).
COPY certs/ /certs/
RUN if [ -s /certs/extra-ca.pem ]; then cat /certs/extra-ca.pem >> /etc/ssl/certs/ca-certificates.crt; fi
ENV NODE_EXTRA_CA_CERTS=/etc/ssl/certs/ca-certificates.crt NEXT_TELEMETRY_DISABLED=1

# dependencies only (cached until package*.json changes)
FROM base AS deps
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund

# the CLI image: generate types, the admin import map and database migrations
#   docker compose run --rm tools npx payload migrate:create <name>
FROM deps AS tools
COPY . .

FROM deps AS builder
COPY . .
RUN npm run build

FROM base AS runner
ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0 MEDIA_DIR=/app/media SEED_DIR=/app/seed
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs \
 && mkdir -p /app/media /app/.next && chown -R nextjs:nodejs /app/media /app/.next
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
# first-run content (the site copy and the five courses), loaded once into an empty database
COPY --chown=nextjs:nodejs seed/ ./seed/
USER nextjs
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s CMD wget -qO- http://127.0.0.1:3000/api/health >/dev/null || exit 1
CMD ["node", "server.js"]
