# Production Dockerfile for MotoVaultPro Backend
# Uses mirrored base images from Gitea Package Registry

# Build argument for registry (defaults to Gitea mirrors, falls back to Docker Hub)
ARG REGISTRY_MIRRORS=git.motovaultpro.com/egullickson/mirrors

# Stage 1: Build stage
FROM ${REGISTRY_MIRRORS}/node:20-alpine AS builder

# Install build dependencies
RUN apk add --no-cache dumb-init git curl

# Set working directory
WORKDIR /app

# Copy package files from backend directory
COPY backend/package*.json ./

# Install all dependencies (including dev for building)
RUN npm install && npm cache clean --force

# Copy logo from frontend for email templates (needed for build)
RUN mkdir -p frontend/public/images/logos
COPY frontend/public/images/logos/motovaultpro-logo-title.png frontend/public/images/logos/

# Copy backend source code
COPY backend/ .

# Build the application (prebuild will encode logo)
ENV DOCKER_BUILD=true
RUN npm run build

# Stage 2: Production runtime
FROM ${REGISTRY_MIRRORS}/node:20-alpine AS production

# Install runtime dependencies only (postgresql-client for backup/restore)
RUN apk add --no-cache dumb-init curl postgresql-client

# Set working directory
WORKDIR /app

# Copy package files and any lock file generated in builder stage
COPY backend/package*.json ./
COPY --from=builder /app/package-lock.json ./

# Install only production dependencies
RUN npm ci --omit=dev && npm cache clean --force

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

# Copy built application from builder stage
COPY --from=builder /app/dist ./dist

# Package migrations at a stable path used by migration runner
# Copy both feature and core migrations so the runner can orchestrate order
ENV MIGRATIONS_DIR=/app/migrations
RUN mkdir -p /app/migrations/features /app/migrations/core
COPY --from=builder /app/src/features /app/migrations/features
COPY --from=builder /app/src/core /app/migrations/core

# Copy entrypoint script for permission checks
COPY backend/scripts/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod 755 /usr/local/bin/docker-entrypoint.sh

# Change ownership to non-root user
RUN chown -R nodejs:nodejs /app

# Switch to non-root user
USER nodejs

# Expose port
EXPOSE 3001

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD node -e "require('http').get('http://localhost:3001/health', (res) => { process.exit(res.statusCode === 200 ? 0 : 1) }).on('error', () => process.exit(1))"

# Use dumb-init with entrypoint for permission checks
ENTRYPOINT ["dumb-init", "--", "/usr/local/bin/docker-entrypoint.sh"]

# Run production application with auto-migrate (idempotent)
CMD ["sh", "-lc", "node dist/_system/migrations/run-all.js && npm start"]
