# Plugin Registry Service Dockerfile
FROM node:20-alpine as base

# Install security updates and necessary packages
RUN apk update && apk upgrade && \
    apk add --no-cache \
    dumb-init \
    curl \
    git \
    && rm -rf /var/cache/apk/*

# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
    adduser -S pluginuser -u 1001

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./
COPY tsconfig.json ./

# Install dependencies
FROM base AS deps
RUN npm ci --only=production && npm cache clean --force

# Build stage
FROM base AS builder
COPY . .
RUN npm ci && npm run build

# Production stage
FROM base AS runner
ENV NODE_ENV=production
ENV PORT=3001

# Copy user and set permissions
USER pluginuser

# Copy built application
COPY --from=builder --chown=pluginuser:nodejs /app/dist ./dist
COPY --from=builder --chown=pluginuser:nodejs /app/src ./src
COPY --from=builder --chown=pluginuser:nodejs /app/package.json ./
COPY --from=builder --chown=pluginuser:nodejs /app/tsconfig.json ./

# Copy production dependencies
COPY --from=deps --chown=pluginuser:nodejs /app/node_modules ./node_modules

# Create necessary directories
USER root
RUN mkdir -p /app/storage /app/logs && \
    chown -R pluginuser:nodejs /app/storage /app/logs
USER pluginuser

# Expose port
EXPOSE 3001

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:3001/health || exit 1

# Use dumb-init to handle signals properly
ENTRYPOINT ["dumb-init", "--"]

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