"""Repository مربوط به اشتراک و دسترسی قابلیت tenant."""
from __future__ import annotations

from uuid import UUID

from sqlalchemy import select
from sqlalchemy.orm import joinedload

from app.models.subscription import TenantFeatureAccess, TenantSubscription
from app.repositories.base import BaseRepository


class SubscriptionRepository(BaseRepository[TenantSubscription]):
    model = TenantSubscription

    async def get_active_by_tenant(self, tenant_id: UUID) -> TenantSubscription | None:
        """آخرین اشتراک tenant را برمی‌گرداند (جدیدترین بر اساس created_at)."""
        stmt = (
            select(TenantSubscription)
            .where(TenantSubscription.tenant_id == tenant_id)
            .order_by(TenantSubscription.created_at.desc())
            .limit(1)
        )
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()


class TenantFeatureAccessRepository(BaseRepository[TenantFeatureAccess]):
    model = TenantFeatureAccess

    async def get(
        self, tenant_id: UUID, feature_id: UUID
    ) -> TenantFeatureAccess | None:
        stmt = select(TenantFeatureAccess).where(
            TenantFeatureAccess.tenant_id == tenant_id,
            TenantFeatureAccess.feature_id == feature_id,
        )
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()
