FROM node:20-alpine AS builder

WORKDIR /app

# Copy package manifests and install dependencies (incl. workspaces)
COPY package.json package-lock.json ./
COPY apps/api/package.json apps/api/package.json
RUN npm ci --workspaces --include-workspace-root

# Copy sources for building (monorepo)
COPY apps/api apps/api/
COPY core core/
COPY adapters adapters/
COPY apps/api/tsconfig.json apps/api/
COPY tsconfig.base.json ./

# Build shared libs + API (so runtime imports resolve)
RUN npx tsc -b core/tsconfig.json adapters/tsconfig.json
RUN npm run build --workspace=@gridpilot/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

# Provide runtime module resolution for @core/* and @adapters/*
COPY --from=builder /app/dist/core /app/node_modules/@core
COPY --from=builder /app/dist/adapters /app/node_modules/@adapters

EXPOSE 3000

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