"""Resolve GitHub App installation id for API/worker calls.

Installation is per GitHub account/org; we store the numeric id on ``workspace_settings`` when
multi-tenant, and fall back to ``GITHUB_INSTALLATION_ID`` for single-tenant deployments.
"""
from __future__ import annotations

from uuid import UUID

from src.config import get_settings
from src.domain.workspaces.repository import WorkspaceSettingsRepository


async def resolve_installation_id_for_workspace(db_factory, workspace_id: UUID) -> int:
    """Return a positive GitHub App installation id or raise ``ValueError``."""
    settings = get_settings()
    async with db_factory() as db:
        ws_settings = await WorkspaceSettingsRepository(db).get_or_create(workspace_id)
        from_db = ws_settings.github_installation_id
        await db.commit()

    if from_db is not None and int(from_db) > 0:
        return int(from_db)

    env_id = int(settings.github_installation_id or 0)
    if env_id > 0:
        return env_id

    raise ValueError(
        "No GitHub App installation id configured. Set GITHUB_INSTALLATION_ID for the worker/API "
        "or store workspace_settings.github_installation_id for this workspace (GitHub → your App → "
        "Install app; the numeric id appears in the installation URL and in the API)."
    )
