"""Commercial Runtime entitlement client — Payment never owns commercial catalogs."""
from __future__ import annotations

from uuid import UUID

import httpx

from app.core.config import settings


class CoreEntitlementClient:
    """Calls Core Commercial Runtime entitlements API (SoT)."""

    async def has_access(
        self, tenant_id: UUID, feature_key: str = "payment.module.enabled"
    ) -> bool:
        if not settings.auth_required or settings.entitlement_stub:
            return True
        url = f"{settings.core_service_url.rstrip('/')}/api/v1/commercial/entitlements/check"
        try:
            async with httpx.AsyncClient(timeout=5.0) as client:
                resp = await client.post(
                    url,
                    json={
                        "tenant_id": str(tenant_id),
                        "feature_key": feature_key,
                        "capability_code": feature_key,
                    },
                )
                if resp.status_code >= 400:
                    return False
                body = resp.json()
                return bool(body.get("has_access") or body.get("allowed"))
        except Exception:
            return False
