# syntax=docker/dockerfile:1
#
# The hosted dashboard only. The clicker cannot run in here — it drives a real
# mouse and keyboard and needs a desktop session — and neither can the
# extension. Both stay on the Windows machine and talk to this over HTTPS.
#
# Debian rather than Alpine: better-sqlite3 publishes glibc prebuilds, and a
# musl image would compile it from source on every build.

# ── deps ─────────────────────────────────────────────────────────────────────
FROM node:24-slim AS deps
WORKDIR /app
# Only used if npm cannot find a prebuilt better-sqlite3 for this Node ABI.
RUN apt-get update && apt-get install -y --no-install-recommends python3 make g++ \
    && rm -rf /var/lib/apt/lists/*
COPY package.json package-lock.json ./
RUN npm ci

# ── prod deps ────────────────────────────────────────────────────────────────
# A separate, dev-free install for the runtime image.
FROM node:24-slim AS proddeps
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends python3 make g++ \
    && rm -rf /var/lib/apt/lists/*
COPY package.json package-lock.json ./
RUN npm ci --omit=dev

# ── build ────────────────────────────────────────────────────────────────────
FROM node:24-slim AS builder
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

# ── run ──────────────────────────────────────────────────────────────────────
FROM node:24-slim AS runner
WORKDIR /app

ENV NODE_ENV=production \
    NEXT_TELEMETRY_DISABLED=1 \
    PORT=3000 \
    HOSTNAME=0.0.0.0 \
    AUTOFIRMER_DB=/data/autotrader.sqlite

RUN groupadd -g 1001 nodejs && useradd -u 1001 -g nodejs -m nextjs

# The SQLite database lives here, on a named volume. Anything written inside the
# image is thrown away on the next deploy, and WAL mode also needs to create
# -wal and -shm files alongside the database, so the directory must be writable.
RUN mkdir -p /data && chown nextjs:nodejs /data

COPY --from=proddeps --chown=nextjs:nodejs /app/node_modules ./node_modules
COPY --from=builder  --chown=nextjs:nodejs /app/.next ./.next
COPY --chown=nextjs:nodejs package.json next.config.mjs ./
COPY --chown=nextjs:nodejs public ./public
# /api/autobuyer/status reads the version out of this manifest and the extension
# reloads itself to match, so the folder has to travel with the server.
COPY --chown=nextjs:nodejs extension ./extension

USER nextjs
EXPOSE 3000

HEALTHCHECK --interval=15s --timeout=10s --start-period=20s --retries=5 \
    CMD node -e "fetch('http://127.0.0.1:3000/api/autobuyer/status').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"

CMD ["npm", "start"]
