# Build stage
FROM node:20-alpine AS builder

WORKDIR /app

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

# Install dependencies (including dev dependencies for build)
RUN npm ci

# Copy source code and configuration
COPY . .

# Build Next.js application with standalone output
RUN npm run build

# Runtime stage
FROM node:20-alpine

# Create non-root user for security
RUN addgroup -g 101 nextjs && \
    adduser -D -u 101 -G nextjs nextjs

WORKDIR /app

# Copy standalone output from builder stage
COPY --from=builder --chown=nextjs:nextjs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nextjs /app/.next/static ./.next/static
COPY --from=builder --chown=nextjs:nextjs /app/public ./public

# Set environment for production
ENV NODE_ENV=production
ENV PORT=3000

# Expose port
EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD node -e "require('http').get('http://localhost:3000/', (r) => {if (r.statusCode !== 200) throw new Error(r.statusCode)})"

# Run as non-root user
USER nextjs

# Start the application
CMD ["node", "server.js"]
