# Stage 1: Base image for building the app
FROM node:lts-alpine AS base

ARG VITE_APP_URL
ARG APP_ENV
ARG BACKEND_URL

# Stage 2: Install dependencies only when needed
FROM base AS deps
WORKDIR /app
COPY package*.json ./
# Try npm ci first, fallback to npm install if lock file is out of sync
RUN npm ci || npm install

# Stage 3: Build the app
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Build arguments for environment variables
ARG VITE_APP_URL
ARG APP_ENV
ENV VITE_APP_URL=${VITE_APP_URL}

RUN npm run build

# Stage 4: Production image with nginx
FROM nginx:alpine AS runner
WORKDIR /app

# Copy built files
COPY --from=builder /app/dist /usr/share/nginx/html

# Create nginx configuration
ARG BACKEND_URL=http://backend:5000
RUN echo "server { \
    listen 80; \
    server_name _; \
    root /usr/share/nginx/html; \
    index index.html; \
    \
    location / { \
        try_files \$uri \$uri/ /index.html; \
    } \
    \
    location /api { \
        proxy_pass ${BACKEND_URL}; \
        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; \
    } \
}" > /etc/nginx/conf.d/default.conf

EXPOSE 80

ENV PORT 80

CMD ["nginx", "-g", "daemon off;"]
