FROM node:20-alpine AS builder

WORKDIR /app

# Copy root package.json and install dependencies (for monorepo)
COPY package.json package-lock.json ./
RUN npm ci

# Copy apps/api and packages for building
COPY apps/api apps/api/
COPY packages core/
COPY apps/api/tsconfig.json apps/api/
COPY tsconfig.base.json ./

# Build the NestJS application (ensuring correct workspace context)
# Run from the root workspace context
# RUN node ./node_modules/@nestjs/cli/bin/nest.js build --workspace=api # Not needed, npm run handles it
RUN npm run build --workspace=api


# Production stage: slim image with only production dependencies
FROM node:20-alpine AS production_final

WORKDIR /app

# Install wget for healthchecks
RUN apk add --no-cache wget

# Copy package files and install production dependencies only
COPY --from=builder /app/package.json ./
COPY --from=builder /app/package-lock.json ./
RUN npm ci --omit=dev

# Copy built application from builder stage
COPY --from=builder /app/apps/api/dist ./apps/api/dist

# Copy packages (needed for runtime dependencies)
COPY --from=builder /app/packages ./packages

EXPOSE 3000

ENV NODE_ENV=production
# Command to run the NestJS application
CMD ["node", "./apps/api/dist/main"]
