FROM node:22-alpine AS builder

WORKDIR /app

COPY package*.json ./
RUN npm install && npm cache clean --force

# --- Runtime image ---
FROM node:22-alpine

# Install runtime dependencies
RUN apk update && \
    apk add --no-cache --repository https://dl-cdn.alpinelinux.org/alpine/edge/community \
        wireguard-tools \
    && apk add --no-cache \
        iptables \
        iproute2 \
        openresolv \
        bash \
        curl \
    && rm -rf /var/cache/apk/*

WORKDIR /app

# Copy node_modules from builder
COPY --from=builder /app/node_modules ./node_modules
COPY package*.json ./

# Copy application source
COPY ./src ./src

# Copy startup script
COPY ./wg/start.sh /app/start.sh
RUN chmod +x /app/start.sh

# Create db directory
RUN mkdir -p /app/db

# Health check: bot responds to /health on port 3000
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD curl -sf http://localhost:3001/health || exit 1

CMD ["/bin/bash", "/app/start.sh"]