FROM python:3.11-slim AS runtime

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

WORKDIR /app

COPY expenses_manager/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY expenses_manager/ .

RUN SECRET_KEY=build-time-placeholder \
    DEBUG=False \
    ALLOWED_HOSTS=localhost \
    python manage.py collectstatic --noinput

# Run as an unprivileged account. /app must belong to it: gunicorn writes its
# control socket there, and pytest its cache in the test image.
RUN useradd --create-home --uid 1000 appuser \
    && chown -R appuser:appuser /app

USER appuser

EXPOSE 8000

CMD ["gunicorn", "expenses_manager.wsgi:application", "--bind", "0.0.0.0:8000"]


# The production image plus the test-only dependencies.
FROM runtime AS test

# pip writes to the system site-packages, so the install runs as root and the
# image then drops back to the unprivileged account.
USER root
RUN pip install --no-cache-dir -r requirements-dev.txt
USER appuser