# syntax=docker/dockerfile:1

# -------------------- Build stage --------------------
FROM node:20-bullseye AS builder
WORKDIR /app

# Copy ONLY package files first (creates cacheable layer)
COPY package*.json ./

# Install dependencies with cache mount for faster rebuilds
RUN --mount=type=cache,target=/root/.npm \
    npm ci

# Copy source files AFTER npm install (only invalidates cache if code changes)
COPY . .

# Build Angular app with cache mount for Angular's build cache
RUN --mount=type=cache,target=/app/.angular/cache \
    npx ng build --configuration=production

# Prune dev dependencies to keep only production deps
RUN npm prune --omit=dev

# -------------------- Runtime stage --------------------
FROM node:20-bullseye-slim AS runner
ENV NODE_ENV=production
WORKDIR /app

# Install curl for healthcheck
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*

# Create required runtime directories
RUN mkdir -p /app/db /app/tmp/downloads /app/vault

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

# Copy production dependencies from builder
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package*.json ./

# Copy config and assets
COPY --from=builder /app/assets ./assets

# Copy database schema
COPY --from=builder /app/db/schema.sql ./db/schema.sql

# Create volume mount points for Obsidian vault
VOLUME ["/app/vault"]

# Expose API/web port
EXPOSE 4000

# Healthcheck against API
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
  CMD curl -fsS http://localhost:4000/api/health || exit 1

# Start the API server (serves the Angular build from ./dist)
CMD ["node", "./server/index.mjs"]