# Build context: learning_ai_invt_trdg/ (monorepo root)
# docker-compose passes GITEA_NPM_TOKEN as a build arg for the private @bytelyst registry
#
# --- Stage 1: Build ---
FROM node:20-alpine AS builder

RUN corepack enable && corepack prepare pnpm@10.6.5 --activate

WORKDIR /app

ARG GITEA_NPM_TOKEN
ARG BYTELYST_PACKAGE_SOURCE=vendor
ENV GITEA_NPM_TOKEN=${GITEA_NPM_TOKEN}
ENV BYTELYST_PACKAGE_SOURCE=${BYTELYST_PACKAGE_SOURCE}

# Copy workspace root files first (layer cache)
COPY .npmrc .pnpmfile.cjs pnpm-workspace.yaml pnpm-lock.yaml* ./
COPY package.json ./package.json
COPY backend/package.json ./backend/package.json
COPY web/package.json ./web/package.json
COPY mobile/package.json ./mobile/package.json

# Vendor packages — @bytelyst/* are file: references that must be present before pnpm install
COPY vendor/ ./vendor/

# Install the workspace graph so shared/ files resolve the same way they do locally.
RUN pnpm install -r

# Copy source (backend + shared types used by tsconfig rootDir "..")
COPY backend/ ./backend/
COPY shared/ ./shared/
WORKDIR /app/backend
RUN pnpm run build

# --- Stage 2: Production ---
FROM node:20-alpine

RUN corepack enable && corepack prepare pnpm@10.6.5 --activate

WORKDIR /app

ARG GITEA_NPM_TOKEN
ARG BYTELYST_PACKAGE_SOURCE=vendor
ENV GITEA_NPM_TOKEN=${GITEA_NPM_TOKEN}
ENV BYTELYST_PACKAGE_SOURCE=${BYTELYST_PACKAGE_SOURCE}

COPY .npmrc .pnpmfile.cjs pnpm-workspace.yaml pnpm-lock.yaml* ./
COPY package.json ./package.json
COPY backend/package.json ./backend/package.json
COPY vendor/ ./vendor/

RUN pnpm install --filter @bytelyst/trading-backend --prod
RUN mkdir -p /app/node_modules && ln -s /app/backend/node_modules/@bytelyst /app/node_modules/@bytelyst

COPY --from=builder /app/backend/dist ./backend/dist

RUN chown -R node:node /app
USER node

WORKDIR /app/backend
EXPOSE 4018
CMD ["node", "dist/backend/src/bootstrap.js"]
