# ============================================
# Stage 1: Build the static bundle with Vite
# ============================================
FROM node:20-alpine AS builder

WORKDIR /app

# Copy manifests first to leverage Docker layer cache
COPY package.json package-lock.json* ./
RUN npm ci --no-audit --no-fund

# Copy the rest of the source
COPY . .

# Build the production bundle (outputs to /app/dist)
RUN npm run build

# ============================================
# Stage 2: Serve with Nginx (production-grade)
# ============================================
FROM nginx:1.27-alpine AS production

# Remove default nginx config and static assets
RUN rm -rf /etc/nginx/conf.d/default.conf /usr/share/nginx/html/*

# Install custom nginx config
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf

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

# Security: run as non-root
RUN chown -R nginx:nginx /usr/share/nginx/html && \
    chown -R nginx:nginx /var/cache/nginx && \
    chown -R nginx:nginx /var/log/nginx && \
    chown -R nginx:nginx /etc/nginx/conf.d && \
    touch /var/run/nginx.pid && \
    chown -R nginx:nginx /var/run/nginx.pid

EXPOSE 80

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

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