# ------------------- Base Stage -------------------
FROM node:20-slim AS base

WORKDIR /app

# Install build dependencies for sqlite3 native module
RUN apt-get update && apt-get install -y \
    python3 \
    make \
    g++ \
    && rm -rf /var/lib/apt/lists/*

COPY package*.json ./

# ------------------- Development Stage -------------------
FROM base AS development

ENV NODE_ENV=development

RUN npm ci

COPY . .

EXPOSE 1458

CMD ["npm", "run", "dev"]

# ------------------- Production Stage -------------------
FROM base AS production

ENV NODE_ENV=production

RUN npm ci --only=production && \
    npm rebuild sqlite3 --build-from-source

COPY . .

# Create runtime dirs owned by the non-root 'node' user (uid 1000).
# This ensures /app/logs and /app/data exist inside the image with correct perms
# even if no volume is mounted at start. Volumes will override at runtime.
RUN mkdir -p /app/logs /app/data && chown -R node:node /app/logs /app/data

EXPOSE 1458

# Run as non-root user (node user in the image has uid 1000).
# On Linux hosts you may need to ensure the host data/logs dirs are owned by 1000:1000
# or use user namespaces / volume permissions.
USER node

CMD ["npm", "start"]