# Multi-stage build for VAPORA Frontend (Leptos CSR)
# Build stage
FROM rust:1.75-alpine AS builder

WORKDIR /usr/src/app

# Install build dependencies
RUN apk add --no-cache \
    musl-dev \
    npm \
    pkgconfig \
    openssl-dev

# Install trunk for WASM building
RUN cargo install trunk --locked

# Install wasm-bindgen-cli
RUN cargo install wasm-bindgen-cli --locked

# Add wasm32 target
RUN rustup target add wasm32-unknown-unknown

# Copy workspace files
COPY Cargo.toml Cargo.lock ./
COPY crates ./crates

# Build frontend
WORKDIR /usr/src/app/crates/vapora-frontend
RUN trunk build --release

# Runtime stage
FROM nginx:alpine

# Remove default nginx config
RUN rm /etc/nginx/conf.d/default.conf

# Create nginx configuration
RUN cat > /etc/nginx/conf.d/default.conf << 'EOF'
server {
    listen 80;
    server_name _;

    root /usr/share/nginx/html;
    index index.html;

    # Gzip compression
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/wasm;

    # Frontend static files
    location / {
        try_files $uri $uri/ /index.html;
        add_header Cache-Control "public, max-age=3600";
    }

    # WASM files need special MIME type
    location ~ \.wasm$ {
        types {
            application/wasm wasm;
        }
        add_header Cache-Control "public, max-age=86400";
    }

    # API proxy
    location /api/ {
        proxy_pass http://vapora-backend:8080/api/;
        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;
    }

    # WebSocket proxy
    location /ws/ {
        proxy_pass http://vapora-backend:8080/ws/;
        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;
    }
}
EOF

# Copy built frontend from builder
COPY --from=builder /usr/src/app/crates/vapora-frontend/dist /usr/share/nginx/html

# Create simple health check file
RUN echo "OK" > /usr/share/nginx/html/health.html

EXPOSE 80

# Health check
HEALTHCHECK --interval=10s --timeout=5s --start-period=5s --retries=3 \
    CMD wget --quiet --tries=1 --spider http://localhost/health.html || exit 1

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