FROM node:20-alpine

WORKDIR /app

# Install server deps first for better layer caching (production only).
COPY server/package*.json server/
RUN npm install --prefix server --omit=dev

# Copy the rest of the repo. .dockerignore keeps node_modules/.env/_reference out,
# so the server deps installed above are preserved.
COPY . .

# Build the client if it is present (added in the frontend phase). Until then the
# server runs API-only and serves a placeholder at /.
RUN if [ -f client/package.json ]; then \
      npm install --prefix client && npm run build --prefix client; \
    else \
      echo "No client/ present — building server-only image"; \
    fi

# Persistent uploads + logs live on mounted volumes.
RUN mkdir -p /app/uploads /app/logs && chown -R node:node /app/uploads /app/logs

# Installed modules are mounted in too (docker-compose.yml), and .dockerignore
# keeps any local modules/ OUT of the image — a module must never be baked in.
# The directory is still created here so a container run without the mount finds
# an empty, writable modules dir rather than no directory at all.
RUN mkdir -p /app/modules && chown node:node /app/modules

USER node

EXPOSE 3000

CMD ["npm", "start", "--prefix", "server"]
