# OpenHamClock Dockerfile
# Multi-stage build for optimized production image

# ============================================
# Stage 1: Build Frontend
# ============================================
FROM node:20-alpine AS builder

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install ALL dependencies (including devDependencies for Vite)
RUN npm install

# Copy source files
COPY . .

# Build the React app with Vite
RUN npm run build

# ============================================
# Stage 2: Production
# ============================================
FROM node:20-alpine AS production

# Set environment
ENV NODE_ENV=production
ENV PORT=3000

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

WORKDIR /app

# Copy package files and install production deps only
COPY package*.json ./
RUN npm install --omit=dev

# Copy server files
COPY server.js ./
COPY config.js ./

# Copy WSJT-X relay agent (served as download to users)
COPY wsjtx-relay ./wsjtx-relay

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

# Copy public folder (for monolithic fallback reference)
COPY public ./public

# Set ownership
RUN chown -R openhamclock:nodejs /app

# Switch to non-root user
USER openhamclock

# Expose ports (3000 = web, 2237 = WSJT-X UDP)
EXPOSE 3000
EXPOSE 2237/udp

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1

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