# Build stage
FROM --platform=linux/amd64 node:18-alpine as build
ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}
WORKDIR /app

# System dependencies with enhanced build tools
RUN apk add --no-cache python3 make g++ curl git libc6-compat

# Clean and prepare npm
RUN npm cache clean --force
RUN npm install -g npm@latest

# Install dependencies with matching versions
COPY package*.json ./
RUN npm ci --no-optional --platform=linux --arch=x64 --libc=musl
RUN npm install -g typescript
RUN npm install --save-dev @types/react-dom
RUN npm install @rollup/rollup-linux-x64-musl
RUN npm install esbuild@0.21.5

# Copy source code and build
COPY . .
RUN npm run build

# Production stage with Nginx
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

# Health check for container monitoring
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
  CMD curl -f http://localhost/ || exit 1

# Expose port and start Nginx
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
