FROM node:18-alpine AS builder

WORKDIR /build

# Copy package files
COPY package*.json ./
RUN npm install --production

# Copy source code
COPY . .

# Build application (if needed)
RUN npm run build 2>/dev/null || true

# Runtime stage
FROM node:18-alpine

# Install runtime dependencies
RUN apk add --no-cache dumb-init

WORKDIR /app

# Copy node_modules and built application
COPY --from=builder /build/node_modules ./node_modules
COPY --from=builder /build/package*.json ./

# Create non-root user
RUN addgroup -g 1001 -S appgroup && \
    adduser -u 1001 -S appuser -G appgroup

USER appuser

EXPOSE 3000

CMD ["dumb-init", "node", "server.js"]
