# Multi-stage build for better layer caching and smaller final image
FROM node:18-alpine AS deps
WORKDIR /app

# Install dumb-init early
RUN apk add --no-cache dumb-init

# Copy package files first to leverage Docker layer caching
COPY package*.json ./

# Install dependencies with optimized settings
RUN npm install --prefer-offline --no-audit --legacy-peer-deps

# Build stage
FROM node:18-alpine AS builder
WORKDIR /app

# Copy dependencies from deps stage
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Set Node.js memory limit for build
ENV NODE_OPTIONS="--max-old-space-size=2048"
ENV NEXT_TELEMETRY_DISABLED=1

# List files to ensure everything is copied correctly
RUN ls -la

# Force clean build - remove any cached build artifacts
RUN rm -rf .next || true

# Build the application with verbose logging
RUN npm run build

# Verify the build output exists
RUN ls -la .next/ || (echo ".next directory not found!" && exit 1)
RUN ls -la .next/standalone/ || (echo ".next/standalone directory not found!" && cat build.log && exit 1)
RUN ls -la .next/static/ || (echo ".next/static directory not found!" && exit 1)

# Production stage
FROM node:18-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

# Install dumb-init for proper signal handling
RUN apk add --no-cache dumb-init

# Create non-root user for security
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# Copy necessary files from builder stage
COPY --from=builder /app/next.config.js* ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json

# Copy built application
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

# Use dumb-init to handle signals properly
ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "server.js"]