FROM node:22-slim AS frontend-builder

ARG PACKAGE

WORKDIR /app

RUN npm install -g pnpm

COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./
COPY packages ./packages
COPY apps ./apps

RUN pnpm install --frozen-lockfile

RUN pnpm --filter ${PACKAGE} build

FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS backend-builder

ARG PACKAGE

ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy

RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --frozen --no-dev --no-install-workspace --package ${PACKAGE}

WORKDIR /app

COPY pyproject.toml uv.lock ./
COPY packages ./packages
COPY apps ./apps

RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-dev --no-editable --package ${PACKAGE}

FROM unit:python3.12-slim AS runtime

ARG PACKAGE

COPY --from=backend-builder --chown=app:app /app/.venv /venv

ENV PATH="/venv/bin:$PATH"

COPY --from=backend-builder --chown=app:app /app/apps/${PACKAGE}/api /api

COPY --from=frontend-builder --chown=app:app /app/apps/${PACKAGE}/dist /index

EXPOSE 80

COPY .containers/unit/unit.json /docker-entrypoint.d/config.json
