# Production image for the blog. Build and run:
#
#   docker build -t yap-blog .
#   docker run -d --name yap-blog -p 3000:3000 --env-file .env \
#     -v yap-blog-uploads:/app/uploads yap-blog
#
# Migrations and seeding are NOT part of the runtime image (they need dev
# dependencies); run them from the `tools` stage against the same database:
#
#   docker build --target tools -t yap-blog-tools .
#   docker run --rm --env-file .env yap-blog-tools npm run db:migrate
#   docker run --rm --env-file .env yap-blog-tools npm run db:seed
#
# In .env, DATABASE_URL must be reachable FROM INSIDE the container —
# `localhost` there means the container itself, not the host.

# Node 24 to match development; its npm 11 is also what wrote
# package-lock.json (npm 10's `npm ci` rejects npm 11 lockfile layouts).
FROM node:24-alpine AS base
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1

FROM base AS deps
COPY package.json package-lock.json ./
RUN npm ci

# Full source + dev dependencies: the build environment, also reused as the
# `tools` stage for drizzle-kit migrations and the seed script.
FROM deps AS tools
COPY . .

FROM tools AS builder
# The build needs no database — every route renders dynamically at request
# time — but importing src/db fail-fasts when DATABASE_URL is unset, so give
# it a placeholder. The pool connects lazily; nothing dials this address.
RUN NEXT_OUTPUT=standalone \
  DATABASE_URL=postgresql://build:build@localhost:5432/placeholder \
  npm run build

FROM base AS runner
ENV NODE_ENV=production HOSTNAME=0.0.0.0 PORT=3000
RUN addgroup --system --gid 1001 nodejs \
  && adduser --system --uid 1001 --ingroup nodejs nextjs
# Pre-create the uploads dir writable so a fresh named volume inherits
# ownership that the non-root server can write to.
RUN mkdir uploads && chown nextjs:nodejs uploads
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
VOLUME /app/uploads
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s \
  CMD wget -qO /dev/null http://127.0.0.1:3000/ || exit 1
CMD ["node", "server.js"]
