# syntax=docker/dockerfile:1.6

FROM node:20-bookworm-slim AS base
WORKDIR /app
ENV NODE_ENV=production

# Install dependencies first to leverage Docker layer caching
COPY package.json package-lock.json ./

FROM base AS build
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
       python3 \
       make \
       g++ \
    && rm -rf /var/lib/apt/lists/*

# Install production deps (will compile native modules like better-sqlite3/serialport if needed)
RUN npm ci --omit=dev

# Copy source
COPY . .

FROM node:20-bookworm-slim AS runtime
WORKDIR /app
ENV NODE_ENV=production

# Runtime OS packages for printing via pdf-to-printer (lp/lpr)
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
       cups-client \
       cups-bsd \
       libcups2 \
       fonts-dejavu-core \
    && rm -rf /var/lib/apt/lists/*

# Copy built app with node_modules from the build stage
COPY --from=build /app /app

# Create volumes for persistent data and user uploads
VOLUME ["/app/data", "/app/public/uploads"]

# Ensure non-root runtime; change ownership so the node user can write to volumes
RUN chown -R node:node /app
USER node

EXPOSE 3000

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

CMD ["npm", "start"]


