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

WORKDIR /build

# Copy audiocontrol source (place the audiocontrol/ folder next to docker-compose.yml)
COPY audiocontrol/package*.json ./
RUN npm ci --quiet

COPY audiocontrol/ ./
RUN npm run build

# ── Stage 2: Nginx (serves app + proxies APIs) ────────────────────────────────
FROM nginx:1.27-alpine

ARG BEOCREATE_HOST=beocreate.local
ARG BEOCREATE_PORT=13141

RUN apk add --no-cache apache2-utils

# Copy built React app
COPY --from=builder /build/dist /var/www/audiocontrol

# Generate nginx.conf with the BeoCreate address substituted
COPY frontend/nginx.conf.template /etc/nginx/templates/default.conf.template
COPY frontend/entrypoint.sh /usr/local/bin/audiocontrol-entrypoint.sh
RUN chmod +x /usr/local/bin/audiocontrol-entrypoint.sh

# nginx-envsubst will substitute $BEOCREATE_HOST and $BEOCREATE_PORT at startup
ENV BEOCREATE_HOST=${BEOCREATE_HOST}
ENV BEOCREATE_PORT=${BEOCREATE_PORT}

EXPOSE 80

HEALTHCHECK --interval=15s --timeout=3s \
    CMD wget -qO- http://127.0.0.1/health || exit 1

ENTRYPOINT ["/usr/local/bin/audiocontrol-entrypoint.sh"]
