# syntax=docker/dockerfile:1
#
# RSSFeed — multi-stage image.
#   build:   installs all deps, typechecks, runs the test suite, builds the web UI
#   deps:    production dependencies of the server only
#   runtime: slim Node image serving API + feeds + UI on one port
# All mutable data (SQLite database) lives on the /data volume.

############################  build  ##############################################
FROM node:24-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
COPY server/package.json ./server/package.json
COPY web/package.json ./web/package.json
RUN --mount=type=cache,target=/root/.npm npm ci

COPY . .
# A broken build or failing test never produces an image.
RUN npm run typecheck --workspace server \
 && npm test --workspace server \
 && npm run build --workspace web

############################  deps  ###############################################
FROM node:24-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
COPY server/package.json ./server/package.json
COPY web/package.json ./web/package.json
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev --workspace server --include-workspace-root=false

############################  runtime  ############################################
FROM node:24-slim AS runtime

ARG GIT_SHA=dev
ENV NODE_ENV=production \
    RSSFEED_DATA_DIR=/data \
    RSSFEED_HOST=0.0.0.0 \
    RSSFEED_PORT=34500 \
    RSSFEED_APP_VERSION=${GIT_SHA} \
    TZ=Europe/Zagreb \
    NODE_OPTIONS=--disable-warning=ExperimentalWarning

LABEL org.opencontainers.image.title="RSSFeed" \
      org.opencontainers.image.description="Self-hosted news feed: merges RSS sources, filters them with plain-language negatives, groups stories and writes Croatian titles and descriptions with a local LLM" \
      org.opencontainers.image.source="https://git.mariosem.es/msemes/RSSFeed" \
      org.opencontainers.image.revision="${GIT_SHA}"

WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/package.json ./package.json
COPY --from=build /app/shared ./shared
COPY --from=build /app/server/package.json ./server/package.json
COPY --from=build /app/server/src ./server/src
COPY --from=build /app/web/dist ./web/dist

RUN mkdir -p /data && chown -R node:node /data
USER node

EXPOSE 34500
VOLUME ["/data"]

HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
  CMD node -e "fetch('http://127.0.0.1:'+(process.env.RSSFEED_PORT||34500)+'/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"

WORKDIR /app/server
CMD ["node", "src/index.ts"]
