# syntax=docker/dockerfile:1

FROM node:22-bookworm-slim AS deps
RUN apt-get update \
  && apt-get install -y --no-install-recommends python3 make g++ \
  && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Do not set NODE_ENV=production here — npm would omit typescript needed for the build stage.
COPY package.json package-lock.json ./
COPY packages/contracts/package.json packages/contracts/
COPY backend/package.json backend/
# Drop root frontend deps (Next/React/UI) so backend image stays lean.
RUN node -e "\
  const fs=require('fs');\
  const p=JSON.parse(fs.readFileSync('package.json','utf8'));\
  p.dependencies={};\
  p.devDependencies={};\
  delete p.scripts;\
  p.workspaces=['packages/*','backend'];\
  fs.writeFileSync('package.json', JSON.stringify(p,null,2)+'\\n');\
"
# Prefer npm ci; if lockfile rejects stripped root package.json, fall back to install.
RUN (npm ci --workspace=@mmapp/contracts --workspace=mikrotik-manager-backend --ignore-scripts \
  || npm install --workspace=@mmapp/contracts --workspace=mikrotik-manager-backend --ignore-scripts) \
  && npm rebuild better-sqlite3

FROM deps AS build
ARG APP_VERSION=dev
ENV APP_VERSION=$APP_VERSION
COPY packages/contracts packages/contracts
COPY backend backend
RUN npm run build -w @mmapp/contracts \
  && npm run build -w mikrotik-manager-backend \
  && npm prune --omit=dev

FROM node:22-bookworm-slim AS runner
WORKDIR /app
ARG APP_VERSION=dev
ENV NODE_ENV=production
ENV PORT=8000
ENV DATABASE_PATH=/app/data/mikrotik.db
ENV APP_VERSION=$APP_VERSION
COPY --from=build /app/package.json /app/package-lock.json ./
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/packages/contracts ./packages/contracts
COPY --from=build /app/backend/dist ./backend/dist
COPY --from=build /app/backend/package.json ./backend/package.json
RUN mkdir -p /app/data
EXPOSE 8000
CMD ["node", "backend/dist/index.js"]
