# syntax=docker/dockerfile:1

########################  Stage 1: build native deps  ########################
# better-sqlite3 is a native module. Building it here (with toolchain present)
# guarantees a correct binary for the target architecture, then we copy the
# finished node_modules into a slim runtime image.
FROM node:22-slim AS deps

# Build tools needed to compile better-sqlite3 if a prebuilt binary isn't used.
RUN apt-get update \
 && apt-get install -y --no-install-recommends python3 make g++ ca-certificates \
 && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY package.json package-lock.json ./
# Install only production dependencies, reproducibly.
RUN npm ci --omit=dev

########################  Stage 2: runtime  ########################
FROM node:22-slim AS runtime

ENV NODE_ENV=production \
    PORT=3000 \
    DB_PATH=/app/data/datahub.db \
    UPLOAD_DIR=/app/uploads \
    BRAND_DIR=/app/brand

# Tini gives us proper signal handling / zombie reaping for the Node process.
RUN apt-get update \
 && apt-get install -y --no-install-recommends tini \
 && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Bring in the already-built dependencies.
COPY --from=deps /app/node_modules ./node_modules

# Application source.
COPY . .

# Persistent data lives in these directories (mounted as volumes at runtime).
# Create them and hand ownership to the unprivileged "node" user that ships
# with the official image.
RUN mkdir -p /app/data /app/uploads /app/brand \
 && chmod +x /app/docker-entrypoint.sh \
 && chown -R node:node /app

USER node

EXPOSE 3000
VOLUME ["/app/data", "/app/uploads", "/app/brand"]

# Basic liveness check against the public login page.
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
  CMD node -e "require('http').get('http://127.0.0.1:'+(process.env.PORT||3000)+'/login.html',r=>process.exit(r.statusCode<500?0:1)).on('error',()=>process.exit(1))"

ENTRYPOINT ["/usr/bin/tini", "--", "/app/docker-entrypoint.sh"]
CMD ["node", "server.js"]
