# ── Stage 1: build the Vite client ───────────────────────────────────────────
FROM node:24-slim AS client-build

WORKDIR /app

COPY client/package*.json client/
RUN npm install --prefix client

COPY client/ client/
RUN npm run build --prefix client

# ── Stage 2: compile the TypeScript server ────────────────────────────────────
FROM node:24-slim AS server-build

# better-sqlite3 has a native addon with no prebuilt binary for this
# platform/Node combo yet — build it from source.
RUN apt-get update -q && apt-get install -y --no-install-recommends python3 make g++ \
  && rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY server/package*.json server/
COPY server/tsconfig.json server/
RUN npm install --prefix server

COPY server/src/ server/src/
RUN npm run build --prefix server

# ── Stage 3: runtime ──────────────────────────────────────────────────────────
FROM node:24-slim

WORKDIR /app

# better-sqlite3 needs to rebuild its native addon here too, then the
# build toolchain is dropped again to keep the runtime image lean.
RUN apt-get update -q && apt-get install -y --no-install-recommends python3 make g++ \
  && rm -rf /var/lib/apt/lists/*

# Production-only server dependencies (no tsx, no typescript)
COPY server/package*.json server/
RUN npm install --prefix server --omit=dev \
  && apt-get purge -y python3 make g++ && apt-get autoremove -y

# Compiled server + built client
COPY --from=server-build /app/server/dist server/dist
COPY --from=client-build /app/client/dist client/dist

# Do NOT copy data/ — that's a mutable runtime volume holding the SQLite
# DB and ciphertext blobs. Baking it into the image would clobber it on
# every redeploy.
ENV NODE_ENV=production
ENV PORT=3000
ENV DATA_DIR=/app/data

EXPOSE 3000

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