"""APIهای اشتراک و بررسی دسترسی قابلیت."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db
from app.core.security import require_authenticated, require_tenant_admin
from app.schemas.subscription import (
    FeatureCheckRequest,
    FeatureCheckResponse,
    SubscriptionCreate,
    SubscriptionRead,
)
from app.services.entitlement_service import EntitlementService
from app.services.subscription_service import SubscriptionService

router = APIRouter(prefix="/tenants/{tenant_id}", tags=["subscription"])


@router.post(
    "/subscription",
    response_model=SubscriptionRead,
    status_code=status.HTTP_201_CREATED,
)
async def create_subscription(
    tenant_id: UUID,
    payload: SubscriptionCreate,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_tenant_admin),
) -> SubscriptionRead:
    subscription = await SubscriptionService(db).create(tenant_id, payload)
    return SubscriptionRead.model_validate(subscription)


@router.get("/subscription", response_model=SubscriptionRead)
async def get_subscription(
    tenant_id: UUID,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_authenticated),
) -> SubscriptionRead:
    subscription = await SubscriptionService(db).get_current(tenant_id)
    return SubscriptionRead.model_validate(subscription)


@router.post("/features/check", response_model=FeatureCheckResponse)
async def check_feature(
    tenant_id: UUID,
    payload: FeatureCheckRequest,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_authenticated),
) -> FeatureCheckResponse:
    result = await EntitlementService(db).evaluate(tenant_id, payload.feature_key)
    return FeatureCheckResponse(
        tenant_id=tenant_id,
        feature_key=payload.feature_key,
        has_access=result.has_access,
        reason=result.reason,
    )
