# BUILD STAGE
FROM elixir:1.18-slim AS build

# Install build dependencies
RUN apt-get update && \
    apt-get install -y build-essential curl git nodejs npm && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app

RUN mix local.hex --force && \
    mix local.rebar --force

ENV MIX_ENV=prod

# R335: Traditional dependency fetching for absolute stability in PROD
COPY mix.exs mix.lock ./
RUN mix do deps.get, deps.compile

# 2. Copy config before compiling source to keep layers stable
COPY config/config.exs config/prod.exs ./config/

# 3. Copy source and compile
COPY lib lib
COPY priv priv
COPY config config

RUN mix do compile, release

# RUN STAGE
FROM elixir:1.18-slim AS run
# curl is here for the compose healthcheck: the release ships no HTTP client,
# so without it the container's health can only be guessed from process
# liveness. With curl the healthcheck hits /api/health, which actually probes
# the DB, identity service, and LiveKit.
RUN apt-get update && \
    apt-get install -y openssl libncurses6 ca-certificates imagemagick ffmpeg libstdc++6 curl && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app
ENV MIX_ENV=prod
ENV HOME=/app

COPY --from=build /app/_build/prod/rel/broarchat_gateway ./
COPY start.sh ./
RUN chmod +x start.sh

CMD ["./start.sh"]
