# ── Stage 1: Build ───────────────────────────────────────────────────────
FROM bytelyst-common-base-web:latest AS builder

WORKDIR /app/web

# Copy web package files
COPY web/package.json ./package.json
COPY web/next.config.ts ./next.config.ts
COPY web/tsconfig.json ./tsconfig.json
COPY web/next-env.d.ts ./next-env.d.ts

# Install web-specific dependencies only
RUN pnpm install --prod --ignore-scripts

# Copy source code
COPY web/src/ ./src/
COPY shared/ ../shared/

# Build arguments
ARG NEXT_PUBLIC_BACKEND_URL
ARG NEXT_PUBLIC_PLATFORM_SERVICE_URL
ENV NEXT_PUBLIC_BACKEND_URL=$NEXT_PUBLIC_BACKEND_URL
ENV NEXT_PUBLIC_PLATFORM_SERVICE_URL=$NEXT_PUBLIC_PLATFORM_SERVICE_URL
ENV NEXT_TELEMETRY_DISABLED=1

# Build web
RUN pnpm run build

# ── Stage 2: Production ───────────────────────────────────────────────────
FROM bytelyst-common-base-web:latest

WORKDIR /app/web

# Copy web package files
COPY web/package.json ./package.json

# Install web-specific dependencies (production only)
RUN pnpm install --prod --ignore-scripts

# Copy built artifacts from builder
COPY --from=builder /app/web/.next/standalone ./
COPY --from=builder /app/web/.next/static ./.next/static

# Environment
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_TLS_REJECT_UNAUTHORIZED=0
ENV PORT=3030
ENV HOSTNAME="0.0.0.0"

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
  CMD node -e "require('http').get('http://localhost:3030', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"

EXPOSE 3030
CMD ["node", "server.js"]
