# ── Stage 1: Install dependencies ────────────────────────────────────────────
FROM node:22-trixie-slim AS deps

WORKDIR /app

ENV DEBIAN_FRONTEND=noninteractive

# Install build tools for native modules (better-sqlite3, pdfkit)
RUN apt-get update && apt-get install -y --no-install-recommends \
		python3 build-essential libsqlite3-dev \
	&& rm -rf /var/lib/apt/lists/*

COPY package.json package-lock.json* ./

# Install all dependencies (including dev for vite build)
RUN npm ci

# ── Stage 2: Build frontend ─────────────────────────────────────────────────
FROM deps AS builder

COPY . .
RUN npm run build

# Prune dev dependencies in-place (avoids a second npm ci)
RUN npm prune --omit=dev

# ── Stage 3: Production image ───────────────────────────────────────────────
FROM node:22-trixie-slim

WORKDIR /app

# Copy production node_modules and built frontend from builder stage
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist

# Copy server code
COPY server/ ./server/

# Create uploads directory
RUN mkdir -p uploads/avatars uploads/branding

ENV NODE_ENV=production
ENV PORT=3001
ENV SQLITE_PATH=/app/data/redlight.db

EXPOSE 3001

# Data volumes for persistent storage
VOLUME ["/app/uploads", "/app/data"]

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