# syntax=docker/dockerfile:1

# --- build stage ---
FROM node:24-alpine AS build

# Pin pnpm for reproducible builds.
RUN corepack enable && corepack prepare pnpm@11.0.5 --activate
WORKDIR /app

# Install dependencies against the lockfile (better-sqlite3 builds its native
# binding here, which is why the build stage is a full toolchain image).
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
RUN apk add --no-cache python3 make g++ \
	&& pnpm install --frozen-lockfile

COPY . .
RUN pnpm build && pnpm prune --prod

# --- runtime stage ---
FROM node:24-alpine AS runtime

ENV NODE_ENV=production
ENV TWINKL_DATA_DIR=/data
WORKDIR /app

# adapter-node output + production node_modules (incl. the compiled better-sqlite3).
COPY --from=build /app/build ./build
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/package.json ./package.json

# SQLite lives on a mounted volume so sessions/cache survive restarts.
RUN mkdir -p /data && addgroup -S twinkl && adduser -S twinkl -G twinkl \
	&& chown -R twinkl:twinkl /app /data
USER twinkl
VOLUME /data

EXPOSE 3000
CMD ["node", "build/index.js"]
