# 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 /etc/nginx/conf.d /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 'server { \
    listen 8080; \
    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/conf.d/default.conf

# Script d'entrée
COPY <<EOF /entrypoint.sh
#!/bin/sh
if [ "\$MODE" = "dev" ]; then
    echo "🔧 Mode DEVELOPPEMENT"
    exec npm run dev -- --host 0.0.0.0 --port 8080
else
    echo "🚀 Mode PRODUCTION"
    exec nginx -g "daemon off;"
fi
EOF

RUN chmod +x /entrypoint.sh

EXPOSE 8080

CMD ["/entrypoint.sh"]