FROM node:20-alpine AS builder

WORKDIR /app

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

# Copy sources and config for building (monorepo)
COPY apps/website apps/website/
COPY core core/
COPY adapters adapters/
COPY scripts scripts/
COPY tsconfig.base.json ./


# Build the Next.js application from the workspace
RUN npm run env:website:merge && npm run build --workspace=@gridpilot/website


# Production stage: slim image with only production dependencies and built files
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 (incl. workspaces)
COPY --from=builder /app/package.json ./
COPY --from=builder /app/package-lock.json ./
COPY --from=builder /app/apps/website/package.json ./apps/website/package.json
RUN npm ci --omit=dev --workspaces --include-workspace-root

# Copy built Next.js application
COPY --from=builder /app/apps/website/.next ./apps/website/.next
COPY --from=builder /app/apps/website/public ./apps/website/public
COPY --from=builder /app/apps/website/package.json ./apps/website/package.json
COPY --from=builder /app/apps/website/next.config.mjs ./apps/website/next.config.mjs


ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
# Run Next.js in production mode (workspace context)
CMD ["npm", "run", "start", "--workspace=@gridpilot/website"]