# ============================================================
# SmartStack Frontend - Multi-stage build
# Image: smartstack-{project}-frontend:{tag}
# ============================================================

# --- Stage 1: Build ---
FROM node:22-alpine AS build
WORKDIR /app

# Build arguments for API URLs (injected at build time)
ARG VITE_API_URL
ARG VITE_WS_URL

# Copy package files for npm cache (context = project root)
COPY web/{{ProjectNameLower}}-web/package.json web/{{ProjectNameLower}}-web/package-lock.json ./

# Install dependencies (cached layer)
RUN npm install

# Copy source code
COPY web/{{ProjectNameLower}}-web/ .

# Build for production
RUN npm run build:prod

# --- Stage 2: Runtime ---
FROM nginx:alpine AS runtime

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

# Inline Nginx configuration
RUN cat > /etc/nginx/conf.d/default.conf << 'NGINX'
server {
    listen 3000;
    server_name _;
    root /usr/share/nginx/html;
    index index.html;

    # SPA routing - fallback to index.html
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Gzip compression
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript image/svg+xml;
    gzip_min_length 256;

    # Static asset caching (1 year for hashed files)
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}
NGINX

EXPOSE 3000

HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
    CMD wget -qO- http://localhost:3000/ || exit 1

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