FROM node:20-alpine AS builder

# Set working directory
WORKDIR /app

# Copy package files
COPY package.json package-lock.json* ./ 

# Install dependencies
RUN npm ci

# Copy all files
COPY . .

# Build the application
RUN npm install && npm run build

# Production image with Nginx
FROM node:20-alpine AS runner

# Install Nginx and supervisor
RUN apk add --no-cache nginx supervisor

# Set working directory
WORKDIR /app

# Set to production environment
ENV NODE_ENV=production

# Copy necessary files from builder stage
COPY --from=builder /app/next.config.mjs ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json

# Create Nginx configuration for custom domain
RUN mkdir -p /etc/nginx/http.d/
RUN rm -f /etc/nginx/http.d/default.conf

# Create Nginx configuration
RUN echo 'server { \
    listen 80; \
    server_name _; \
    \
    location / { \
    proxy_pass http://localhost:3000; \
    proxy_http_version 1.1; \
    proxy_set_header Upgrade $http_upgrade; \
    proxy_set_header Connection "upgrade"; \
    proxy_set_header Host $host; \
    proxy_set_header X-Real-IP $remote_addr; \
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; \
    proxy_set_header X-Forwarded-Proto $scheme; \
    proxy_cache_bypass $http_upgrade; \
    } \
    }' > /etc/nginx/http.d/nextjs.conf

# Configure supervisord
RUN mkdir -p /etc/supervisor.d/
RUN echo '[supervisord]' > /etc/supervisor.d/supervisord.conf
RUN echo 'nodaemon=true' >> /etc/supervisor.d/supervisord.conf
RUN echo '' >> /etc/supervisor.d/supervisord.conf
RUN echo '[program:nextjs]' >> /etc/supervisor.d/supervisord.conf
RUN echo 'command=npm start' >> /etc/supervisor.d/supervisord.conf
RUN echo 'directory=/app' >> /etc/supervisor.d/supervisord.conf
RUN echo 'autostart=true' >> /etc/supervisor.d/supervisord.conf
RUN echo 'autorestart=true' >> /etc/supervisor.d/supervisord.conf
RUN echo 'stderr_logfile=/var/log/nextjs.err.log' >> /etc/supervisor.d/supervisord.conf
RUN echo 'stdout_logfile=/var/log/nextjs.out.log' >> /etc/supervisor.d/supervisord.conf
RUN echo '' >> /etc/supervisor.d/supervisord.conf
RUN echo '[program:nginx]' >> /etc/supervisor.d/supervisord.conf
RUN echo 'command=nginx -g "daemon off;"' >> /etc/supervisor.d/supervisord.conf
RUN echo 'autostart=true' >> /etc/supervisor.d/supervisord.conf
RUN echo 'autorestart=true' >> /etc/supervisor.d/supervisord.conf
RUN echo 'stderr_logfile=/var/log/nginx.err.log' >> /etc/supervisor.d/supervisord.conf
RUN echo 'stdout_logfile=/var/log/nginx.out.log' >> /etc/supervisor.d/supervisord.conf

# Expose both the Next.js port and Nginx port
EXPOSE 3000 80

# Start supervisor which will start both Next.js and Nginx
CMD ["supervisord", "-c", "/etc/supervisor.d/supervisord.conf"]