# ── Stage 1: build ───────────────────────────────────────────────────────────
# Needs build tools (python3, make, g++) to compile better-sqlite3 native addon
FROM node:22-alpine AS builder

RUN apk add --no-cache python3 make g++

WORKDIR /app
COPY package*.json ./
RUN npm ci --include=dev

COPY . .
RUN npm run build

# ── Stage 2: production ───────────────────────────────────────────────────────
# Lean image with only the runtime artifacts
FROM node:22-alpine

ENV NODE_ENV=production \
    PORT=3000 \
    DATA_DIR=/app/data

WORKDIR /app

# Copy only production dependencies (re-install native modules for final arch)
COPY package*.json ./
RUN apk add --no-cache python3 make g++ \
  && npm ci --omit=dev \
  && apk del python3 make g++

# Copy server source and built frontend
COPY server/ ./server/
COPY --from=builder /app/dist ./dist/

RUN mkdir -p /app/data

VOLUME ["/app/data"]
EXPOSE 3000

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