# ---------- Build stage ----------
FROM node:22-alpine AS build
WORKDIR /app

COPY package.json package-lock.json ./
RUN npm ci

COPY . .
RUN npm run build

# ---------- Runtime stage ----------
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production

# production dependencies only (ws) + su-exec for privilege dropping
COPY package.json package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force && \
    apk add --no-cache su-exec

COPY server/server.mjs server/server.mjs
COPY server/db.mjs server/db.mjs
COPY shared/ shared/
COPY --from=build /app/dist dist/
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# persistent account/progress database (mount a volume here on the host)
RUN mkdir -p /app/data
VOLUME ["/app/data"]

EXPOSE 3001
ENV PORT=3001
ENV DATA_DIR=/app/data

# The entrypoint fixes permissions on bind-mounted /app/data and drops
# privileges to the unprivileged "node" user before running the app.
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
CMD ["node", "server/server.mjs"]

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD node -e "fetch('http://localhost:3001/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
