# Build stage
FROM node:22-alpine AS build

WORKDIR /app

# Copy package files and install dependencies
COPY package*.json ./
RUN npm ci --only=production

# Copy source code
COPY . .

# Build the app
RUN npm run build

# Production stage
FROM node:22-alpine

# Create app directory with non-root user
WORKDIR /app
RUN addgroup -S appgroup && adduser -S appuser -G appgroup && \
    chown -R appuser:appgroup /app

# Copy built assets from build stage
COPY --from=build --chown=appuser:appgroup /app/node_modules ./node_modules
COPY --from=build --chown=appuser:appgroup /app/.next ./.next
COPY --from=build --chown=appuser:appgroup /app/public ./public
COPY --from=build --chown=appuser:appgroup /app/package.json ./package.json
COPY --from=build --chown=appuser:appgroup /app/next.config.js ./next.config.js

# Security best practices
ENV NODE_ENV=production
RUN npm prune --production

# Set permissions and switch to non-root user
USER appuser

# Create health check endpoint
COPY --from=build --chown=appuser:appgroup /app/health.js ./health.js

# Expose port
EXPOSE 3000

# Start the application
CMD ["npm", "start"]
