# syntax=docker/dockerfile:1

# Stage 1: Install dependencies (includes devDeps needed for build)
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

# Stage 2: Build the application
FROM node:22-alpine AS build
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npx prisma generate
RUN npm run build
# Drop devDependencies so the production image stays small.
RUN npm prune --omit=dev

# Stage 3: Production runtime image
FROM node:22-alpine AS production
WORKDIR /app

# Embed the version (build-time) so /api/health can echo it later.
ARG VERSION=0.0.0
ENV APP_VERSION=$VERSION

# Install curl for the entrypoint healthcheck. Tini for proper signal handling.
RUN apk add --no-cache curl tini

RUN addgroup -S appgroup && adduser -S appuser -G appgroup

COPY --from=build --chown=appuser:appgroup /app/build ./build
COPY --from=build --chown=appuser:appgroup /app/node_modules ./node_modules
COPY --from=build --chown=appuser:appgroup /app/package.json ./
COPY --from=build --chown=appuser:appgroup /app/prisma ./prisma

# Persistent data dir + uploads subdir. The named volume mount in
# docker-compose targets /app/data, so uploads survive container rebuilds.
RUN mkdir -p /app/data /app/data/uploads /app/data/uploads/wallpapers /app/data/backups \
	&& chown -R appuser:appgroup /app /app/data

USER appuser

ENV NODE_ENV=production
ENV APP_PORT=3000
ENV APP_HOST=0.0.0.0
ENV UPLOADS_DIR=/app/data/uploads

EXPOSE 3000

HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
	CMD curl -sf http://localhost:3000/api/health || exit 1

# Entrypoint:
#   - Always run `prisma migrate deploy`. On an empty DB this creates the schema
#     from the migration history (no separate `db push` bootstrap needed); on an
#     existing DB it applies pending migrations only. No silent fallback — drift
#     and migration failures surface loudly.
#   - Default ORIGIN to localhost:APP_PORT so dev compose works, but production
#     deployments MUST set ORIGIN to the public URL for Secure cookies.
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["sh", "-c", "npx prisma migrate deploy && ORIGIN=${ORIGIN:-http://localhost:${APP_PORT:-3000}} node build"]
