# Stage 1: Build Stage
FROM node:18-alpine AS builder

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm ci

# Copy source code
COPY . .

# Build Next.js application
RUN npm run build

# Stage 2: Production Stage with Nginx
FROM nginx:alpine

# Install Node.js for Next.js standalone mode
RUN apk add --no-cache nodejs

# Copy nginx configuration
COPY deployment/container/nginx.conf /etc/nginx/nginx.conf

# Copy built Next.js application from builder
COPY --from=builder /app/.next/standalone /app
COPY --from=builder /app/.next/static /app/.next/static
COPY --from=builder /app/public /app/public

# Create health check endpoint
RUN echo '<!DOCTYPE html><html><body><h1>OK</h1></body></html>' > /usr/share/nginx/html/health.html

# Copy runtime-env.js template (will be replaced by ConfigMap in K8s)
COPY public/runtime-env.js /usr/share/nginx/html/runtime-env.js

# Create startup script
RUN echo '#!/bin/sh' > /start.sh && \
    echo 'cd /app && HOSTNAME=0.0.0.0 PORT=3000 node server.js &' >> /start.sh && \
    echo 'sleep 3' >> /start.sh && \
    echo 'nginx -g "daemon off;"' >> /start.sh && \
    chmod +x /start.sh

EXPOSE 8080

CMD ["/bin/sh", "/start.sh"]
