# syntax=docker/dockerfile:1.6
#
# VYNDR Express backend (port 3001).
#
# Multi-stage build:
#   1. deps   — install production deps with a clean lockfile
#   2. runner — copy src/, poller/, scripts/, node_modules and start
#
# The Next.js frontend ships in a separate image (web/Dockerfile). PM2
# pollers can run inside this image via `pm2-runtime` or as a sibling
# container — production deploys use a sibling so a poller crash doesn't
# restart the API.
#
# Build:  docker build -t vyndr-api .
# Run:    docker run -p 3001:3001 --env-file .env vyndr-api

# --- deps stage ---
FROM node:20-alpine AS deps
WORKDIR /app

# package-lock.json is the source of truth — npm ci reproduces it exactly.
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --no-audit --no-fund

# --- runner stage ---
FROM node:20-alpine AS runner
WORKDIR /app

# curl is used by the /api/health smoke check (Coolify HEALTHCHECK), and
# postgresql-client lets the in-container migrations script run if needed.
RUN apk add --no-cache curl tini

ENV NODE_ENV=production \
    PORT=3001

# Non-root user — the container should never run as uid 0 even if the
# host accidentally maps a privileged port.
RUN addgroup -S vyndr && adduser -S vyndr -G vyndr

COPY --from=deps /app/node_modules ./node_modules
COPY package.json package-lock.json ./
COPY src ./src
COPY poller ./poller
COPY scripts ./scripts
COPY supabase ./supabase

# Persistent volume for JSONL training data. Coolify mounts this path so
# resolutions survive redeploys.
RUN mkdir -p /app/data/training && chown -R vyndr:vyndr /app/data

USER vyndr

EXPOSE 3001

# tini reaps zombies cleanly when Node spawns child processes (e.g., the
# embedded Python pre-checks the orchestrator may run during a slate).
ENTRYPOINT ["/sbin/tini", "--"]

HEALTHCHECK --interval=30s --timeout=10s --start-period=20s --retries=3 \
  CMD curl -fsS http://127.0.0.1:3001/api/health || exit 1

CMD ["node", "src/server.js"]
