# syntax=docker/dockerfile:1.7

FROM node:20-alpine AS deps
WORKDIR /app

# Build dependencies for native Node modules (better-sqlite3).
RUN apk add --no-cache python3 make g++

COPY package*.json ./
# Use npm cache between builds; fallback to npm install when lock file is absent.
RUN --mount=type=cache,target=/root/.npm \
    if [ -f package-lock.json ]; then \
      npm ci --omit=dev --no-audit --no-fund; \
    else \
      npm install --omit=dev --no-audit --no-fund; \
    fi

FROM node:20-alpine AS runtime
WORKDIR /app

ENV NODE_ENV=production \
    LANG=C.UTF-8 \
    LC_ALL=C.UTF-8 \
    PORT=3000 \
    DB_PATH=/data/intradesk.db

# Runtime libs required by native modules.
RUN apk add --no-cache libstdc++

COPY --from=deps /app/node_modules ./node_modules
COPY server.js refresh-service.js ./
COPY public ./public

RUN mkdir -p /data

ARG GIT_COMMIT=unknown
LABEL org.opencontainers.image.revision=$GIT_COMMIT

EXPOSE 3000

HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
  CMD node -e "const http=require('http');const req=http.get('http://127.0.0.1:3000/healthz',res=>process.exit(res.statusCode===200?0:1));req.on('error',()=>process.exit(1));"

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