"""Control-plane backed tenant registry.

This module centralizes reads from the control plane so the rest of the
platform can work with a single registry abstraction.
"""

from __future__ import annotations

from sqlalchemy import select

from config.control_plane import get_control_plane_session
from platform.tenants.models import Tenant, TenantDomain, TenantApp


class TenantRegistry:
    """Read tenant metadata from the control-plane database."""

    def get_tenant(self, tenant_id: str) -> Tenant | None:
        with get_control_plane_session() as session:
            return session.get(Tenant, tenant_id)

    def get_tenant_by_domain(self, domain: str) -> Tenant | None:
        normalized = (domain or "").strip().lower()
        if not normalized:
            return None
        with get_control_plane_session() as session:
            stmt = (
                select(Tenant)
                .join(TenantDomain, TenantDomain.tenant_id == Tenant.tenant_id)
                .where(TenantDomain.domain == normalized, Tenant.is_active.is_(True))
                .limit(1)
            )
            return session.execute(stmt).scalar_one_or_none()

    def get_tenant_app(self, tenant_id: str, app_id: str) -> TenantApp | None:
        with get_control_plane_session() as session:
            stmt = (
                select(TenantApp)
                .where(
                    TenantApp.tenant_id == tenant_id,
                    TenantApp.app_id == app_id,
                    TenantApp.is_enabled.is_(True),
                )
                .limit(1)
            )
            return session.execute(stmt).scalar_one_or_none()

