# Portal umbrella — Elixir/Phoenix web apps
# Build image stays at 1.19.5 until hexpm publishes 1.20.0 stable.
# Dev shell uses 1.20.0-rc.4 via flake.nix.
#
# Two image targets:
#   docker build --target my    -t .../centralcloud-my:VERSION .
#   docker build --target staff -t .../centralcloud-staff:VERSION .

FROM hexpm/elixir:1.19.5-erlang-28.3.1-debian-trixie-20260202-slim AS build

RUN apt-get update -y && apt-get install -y --no-install-recommends \
    build-essential git npm ca-certificates \
  && apt-get clean && rm -rf /var/lib/apt/lists/*

WORKDIR /app

ENV MIX_ENV=prod

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

# Umbrella root + all sub-app deps files (layer-cache friendly)
COPY mix.exs mix.lock ./
COPY apps/centralcloud_core/mix.exs   ./apps/centralcloud_core/
COPY apps/centralcloud_my/mix.exs     ./apps/centralcloud_my/
COPY apps/centralcloud_staff/mix.exs  ./apps/centralcloud_staff/

RUN mix deps.get --only prod && mix deps.compile

COPY config            ./config
COPY apps/centralcloud_core   ./apps/centralcloud_core
COPY apps/centralcloud_my     ./apps/centralcloud_my
COPY apps/centralcloud_staff  ./apps/centralcloud_staff
COPY rel               ./rel

RUN mix compile

# Install Tailwind CLI and compile CSS for both apps
RUN mix tailwind.install --if-missing
RUN mix tailwind staff --minify && mix tailwind my --minify

# Copy phoenix.min.js + phoenix_live_view.min.js to the my app (my app's priv/static is empty)
RUN cp apps/centralcloud_staff/priv/static/phoenix.min.js \
        apps/centralcloud_my/priv/static/ && \
    cp apps/centralcloud_staff/priv/static/phoenix_live_view.min.js \
        apps/centralcloud_my/priv/static/

RUN mix release centralcloud_my && \
    mix release centralcloud_staff

# ── Shared runtime base ───────────────────────────────────────────────────────
FROM debian:trixie-slim AS runtime-base

RUN apt-get update -y && apt-get install -y --no-install-recommends \
    libstdc++6 openssl libncurses6 locales ca-certificates \
  && apt-get clean && rm -rf /var/lib/apt/lists/*

RUN useradd --create-home --shell /bin/sh app

WORKDIR /app
RUN chown app:app /app

USER app

ENV HOME=/app PHX_SERVER=true

# ── centralcloud-my ───────────────────────────────────────────────────────────
FROM runtime-base AS my

COPY --from=build --chown=app:app /app/_build/prod/rel/centralcloud_my ./

RUN ln -s /app/bin/centralcloud_my /app/bin/migrate || true

CMD ["/app/bin/server"]

# ── centralcloud-staff ────────────────────────────────────────────────────────
FROM runtime-base AS staff

COPY --from=build --chown=app:app /app/_build/prod/rel/centralcloud_staff ./

RUN ln -s /app/bin/centralcloud_staff /app/bin/migrate || true

CMD ["/app/bin/server"]
