# === Stage 1: Build Tool & Webapp ===
FROM node:22-bookworm-slim AS builder
WORKDIR /app

# Install root dependencies
COPY package*.json ./
RUN npm ci || npm install

# Install webapp dependencies
COPY webapp/package*.json ./webapp/
WORKDIR /app/webapp
RUN npm ci || npm install
WORKDIR /app

# Copy full source tree
COPY tsconfig.json ./
COPY src/ ./src/
COPY bin/ ./bin/
COPY webapp/ ./webapp/

# Build tool CLI and Webapp Vite assets
RUN npm run build
RUN cd webapp && npm run build

# === Stage 2: Final Production Image ===
FROM node:22-bookworm-slim
WORKDIR /app

# System dependencies (git fuer Vault sync, tini fuer PID 1, curl fuer Healthchecks)
RUN apt-get update && apt-get install -y --no-install-recommends \
    tini \
    git \
    bash \
    curl \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# QMD Hybrid-Suche
RUN npm install -g @tobilu/qmd

# Production Server dependencies
COPY package*.json ./
RUN npm install --omit=dev

# Compiled Tool CLI & Server
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/bin ./bin
COPY server.mjs ./
COPY entrypoint.sh ./
RUN chmod +x entrypoint.sh ./bin/*.mjs

# Webapp Build Assets
COPY --from=builder /app/webapp/dist ./webapp/dist

# Environment Defaults
ENV NODE_ENV=production
ENV PORT=5173
ENV MINDOMAT_VAULT_PATH=/vault
ENV QMD_CACHE_DIR=/data

EXPOSE 5173 8181

ENTRYPOINT ["/usr/bin/tini", "--", "/app/entrypoint.sh"]
