# Build stage
FROM node:18-alpine AS build

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies with cache mount
RUN --mount=type=cache,target=/root/.npm \
    npm i -g npm@10 \
  && npm ci --prefer-offline --no-audit --no-fund || npm install --no-audit --no-fund

# Copy source code
COPY . .

# Build the app with production settings
ENV NODE_ENV=production
# Disable ESLint during build to avoid CRA/ESLint v9 plugin incompatibilities
ENV DISABLE_ESLINT_PLUGIN=true
# Disable source maps to reduce memory usage
ENV GENERATE_SOURCEMAP=false
# Reduce memory footprint - use 1.5GB with smaller semi-space for better GC
ENV NODE_OPTIONS="--openssl-legacy-provider --max-old-space-size=1536"
# Limit webpack parallelism to reduce memory usage
ENV CI=true

# Clean npm cache before build to free up memory
RUN npm cache clean --force 2>/dev/null || true

# Build with memory optimization
RUN --mount=type=cache,target=/root/.npm \
    npm run build

# Production stage
FROM nginx:alpine

# Remove default nginx static assets
RUN rm -rf /usr/share/nginx/html/*

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

# Copy nginx config
COPY nginx.conf /etc/nginx/conf.d/default.conf

# Set proper permissions
RUN chown -R nginx:nginx /usr/share/nginx/html && \
    chmod -R 755 /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

# Switch to non-root user
USER nginx

# Expose port 80
EXPOSE 80

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