# Production Dockerfile for MotoVaultPro Frontend
# Uses mirrored base images from Gitea Package Registry

# Build argument for registry (defaults to Gitea mirrors, falls back to Docker Hub)
ARG REGISTRY_MIRRORS=git.motovaultpro.com/egullickson/mirrors

# Stage 1: Base with dependencies
FROM ${REGISTRY_MIRRORS}/node:20-alpine AS base
RUN apk add --no-cache dumb-init curl
WORKDIR /app
COPY package*.json ./

# Stage 2: Dependencies installation
FROM base AS deps
RUN npm install && npm cache clean --force

# Stage 3: Build stage
FROM deps AS build

# Accept build arguments for environment variables
ARG VITE_AUTH0_DOMAIN
ARG VITE_AUTH0_CLIENT_ID
ARG VITE_AUTH0_AUDIENCE
ARG VITE_API_BASE_URL
ARG VITE_STRIPE_PUBLISHABLE_KEY

# Set environment variables from build args
ENV VITE_AUTH0_DOMAIN=$VITE_AUTH0_DOMAIN
ENV VITE_AUTH0_CLIENT_ID=$VITE_AUTH0_CLIENT_ID
ENV VITE_AUTH0_AUDIENCE=$VITE_AUTH0_AUDIENCE
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
ENV VITE_STRIPE_PUBLISHABLE_KEY=$VITE_STRIPE_PUBLISHABLE_KEY

COPY . .
RUN npm run build

# Stage 4: Production stage with nginx
FROM ${REGISTRY_MIRRORS}/nginx:alpine AS production

# Add curl for healthchecks
RUN apk add --no-cache curl

# Create non-root user compatible with nginx
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nodejs -u 1001 -G nginx

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

# Copy nginx configuration
COPY nginx.conf /etc/nginx/nginx.conf

# Copy and prepare config loader script
COPY scripts/load-config.sh /app/load-config.sh
RUN chmod +x /app/load-config.sh

# Set environment variable for secrets directory
ENV SECRETS_DIR=/run/secrets

# Set up proper permissions for nginx with non-root user
RUN chown -R nodejs:nginx /usr/share/nginx/html && \
    chown -R nodejs:nginx /var/cache/nginx && \
    chown -R nodejs:nginx /var/log/nginx && \
    chown -R nodejs:nginx /etc/nginx/conf.d && \
    chown nodejs:nginx /etc/nginx/nginx.conf && \
    touch /var/run/nginx.pid && \
    chown -R nodejs:nginx /var/run/nginx.pid && \
    chown nodejs:nginx /app/load-config.sh

# Switch to non-root user
USER nodejs

# Expose ports
EXPOSE 3000 3443

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

# Start: load config then start nginx
CMD ["sh", "-c", "/app/load-config.sh && nginx -g 'daemon off;'"]