# Build context: repo root (docker compose sets context: .)
FROM node:22-alpine AS builder
RUN corepack enable && corepack prepare pnpm@10 --activate
WORKDIR /app

# Copy workspace config + lockfile for dependency resolution
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml tsconfig.base.json ./

# Copy all package.json files (pnpm needs these for workspace resolution)
COPY packages/errors/package.json packages/errors/
COPY packages/cosmos/package.json packages/cosmos/
COPY packages/config/package.json packages/config/
COPY packages/auth/package.json packages/auth/
COPY packages/api-client/package.json packages/api-client/
COPY packages/fastify-core/package.json packages/fastify-core/
COPY packages/logger/package.json packages/logger/
COPY packages/react-auth/package.json packages/react-auth/
COPY packages/design-tokens/package.json packages/design-tokens/
COPY packages/testing/package.json packages/testing/
COPY services/billing-service/package.json services/billing-service/

# Install all workspace deps
RUN pnpm install --frozen-lockfile

# Copy source
COPY packages/ packages/
COPY services/billing-service/tsconfig.json services/billing-service/
COPY services/billing-service/src/ services/billing-service/src/

# Build packages first, then service
RUN pnpm -r --filter @lysnrai/billing-service... build

# Deploy to isolated directory (production deps only)
RUN pnpm --filter @lysnrai/billing-service deploy /app/deploy

# ── Production ─────────────────────────────────────────────
FROM node:22-alpine
WORKDIR /app
COPY --from=builder /app/deploy ./
ENV NODE_ENV=production
EXPOSE 4002
CMD ["node", "dist/server.js"]
