# ── Build Stage ──────────────────────────────────────────────────────────────
FROM node:20-alpine AS builder

WORKDIR /app

# Install build dependencies for better-sqlite3 native addon + OpenSSL for HTTPS
RUN apk add --no-cache python3 make g++ openssl

COPY package.json ./
RUN npm install --production=false

# ── Production Stage ─────────────────────────────────────────────────────────
FROM node:20-alpine

# Install runtime dependencies for better-sqlite3 + ffmpeg for MKV transmuxing
RUN apk add --no-cache python3 openssl ffmpeg

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

WORKDIR /app

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

# Create data directory with correct permissions
RUN mkdir -p /app/src/data && chown -R nexstream:nexstream /app

# Switch to non-root user
USER nexstream

EXPOSE 3091
EXPOSE 3443

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:3091/health || exit 1

ENV NODE_ENV=production
ENV PORT=3091
ENV HTTPS_PORT=3443
# Self-signed cert/key paths (mounted via volume in production)
ENV HTTPS_CERT=/app/src/data/tls/fullchain.pem
ENV HTTPS_KEY=/app/src/data/tls/privkey.pem

CMD ["node", "src/index.js"]
