# Multi-stage build for React Vite application
# Multi-platform support for AMD64 and ARM64
FROM --platform=$BUILDPLATFORM node:20-alpine AS builder

# Install git (required for pnpm)
RUN apk add --no-cache git

# Set working directory
WORKDIR /app

# Install pnpm directly without corepack
RUN npm install -g pnpm@latest

# Copy package files
COPY package.json pnpm-lock.yaml ./

# Install dependencies using pnpm
RUN pnpm install --frozen-lockfile

# Copy source code
COPY . .

# Build the application
RUN pnpm run build

# Production stage with Apache
FROM httpd:2.4-alpine AS production

# Install necessary packages
RUN apk add --no-cache bash

# Copy built application from builder stage
COPY --from=builder /app/build /usr/local/apache2/htdocs/

# Copy Apache configuration
COPY docker/apache.conf /usr/local/apache2/conf/httpd.conf

# Copy .htaccess file for URL rewriting
COPY docker/.htaccess /usr/local/apache2/htdocs/.htaccess

# Copy entrypoint script
COPY docker/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh

# Expose port 80
EXPOSE 80

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

# Start Apache using entrypoint script
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]