# Stage 1 : Build prod
FROM node:20-alpine AS builder

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .

ARG VITE_API_URL=https://api.lediscord.com
ARG VITE_APP_URL=https://lediscord.com
ARG VITE_UPLOAD_URL=https://api.lediscord.com/uploads

ENV VITE_API_URL=$VITE_API_URL
ENV VITE_APP_URL=$VITE_APP_URL
ENV VITE_UPLOAD_URL=$VITE_UPLOAD_URL

RUN npm run build

# Stage 2 : Image finale avec les deux modes
FROM node:20-alpine

RUN apk add --no-cache nginx && mkdir -p /run/nginx

WORKDIR /app

# Copier les sources pour le mode dev
COPY package*.json ./
RUN npm ci

COPY . .

# Copier le build prod
COPY --from=builder /app/dist /usr/share/nginx/html

# Config nginx
RUN echo 'worker_processes auto; \
events { worker_connections 1024; } \
http { \
    include /etc/nginx/mime.types; \
    default_type application/octet-stream; \
    sendfile on; \
    keepalive_timeout 65; \
    gzip on; \
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; \
    server { \
        listen 8082; \
        root /usr/share/nginx/html; \
        index index.html; \
        location / { \
            try_files $uri $uri/ /index.html; \
        } \
        location /assets { \
            expires 1y; \
            add_header Cache-Control "public, immutable"; \
        } \
    } \
}' > /etc/nginx/nginx.conf

# Script d'entrée
RUN echo '#!/bin/sh' > /entrypoint.sh && \
    echo 'if [ "$MODE" = "dev" ]; then' >> /entrypoint.sh && \
    echo '    echo "🔧 Mode DEVELOPPEMENT"' >> /entrypoint.sh && \
    echo '    exec npm run dev -- --host 0.0.0.0 --port 8082' >> /entrypoint.sh && \
    echo 'else' >> /entrypoint.sh && \
    echo '    echo "🚀 Mode PRODUCTION"' >> /entrypoint.sh && \
    echo '    exec nginx -g "daemon off;"' >> /entrypoint.sh && \
    echo 'fi' >> /entrypoint.sh && \
    chmod +x /entrypoint.sh

EXPOSE 8082

CMD ["/entrypoint.sh"]