# ── Stage 1: Build ─────────────────────────────────────────
FROM node:22-alpine AS builder
WORKDIR /app

# native build deps (better-sqlite3 etc)
RUN apk add --no-cache python3 make g++

# install ALL deps (vite needs dev deps) — npm ci for a reproducible, lock-pinned
# build that matches CI (which also uses npm ci).
COPY package*.json ./
RUN npm ci

# copy full project
COPY . .

# build frontend
RUN npm run build


# ── Stage 2: Runtime ───────────────────────────────────────
FROM node:22-alpine
WORKDIR /app

# minimal tools for debugging inside container + privilege drop in entrypoint
RUN apk add --no-cache bash nano su-exec

# create non-root user
RUN addgroup -S bill && adduser -S bill -G bill

# copy EVERYTHING from builder (no missing files)
COPY --from=builder /app ./
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh

# setup persistent data dirs and a writable fallback backup dir
RUN mkdir -p /data/db /data/backups /app/backups \
    && chown -R bill:bill /data /app/backups \
    && chmod 700 /data/db /data/backups /app/backups \
    && chmod +x /usr/local/bin/docker-entrypoint.sh

ENV NODE_ENV=production \
    PORT=3000 \
    DB_PATH=/data/db/bills.db \
    BACKUP_PATH=/data/backups

EXPOSE 3000
VOLUME ["/data"]

# Liveness probe against the unauthenticated /api/health route (uses node, which
# is always present — no curl/wget needed).
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
  CMD node -e "require('http').get('http://127.0.0.1:'+(process.env.PORT||3000)+'/api/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["node", "server.js"]
