"""Repository مربوط به TenantMembership."""
from __future__ import annotations

from typing import Sequence
from uuid import UUID

from sqlalchemy import func, select

from app.models.enums import MembershipStatus
from app.models.membership import TenantMembership
from app.repositories.base import BaseRepository


class TenantMembershipRepository(BaseRepository[TenantMembership]):
    model = TenantMembership

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

    async def list_by_user(self, user_id: UUID) -> Sequence[TenantMembership]:
        stmt = select(TenantMembership).where(TenantMembership.user_id == user_id)
        result = await self.session.execute(stmt)
        return result.scalars().all()

    async def list_by_tenant(self, tenant_id: UUID) -> Sequence[TenantMembership]:
        stmt = select(TenantMembership).where(TenantMembership.tenant_id == tenant_id)
        result = await self.session.execute(stmt)
        return result.scalars().all()

    async def count_active_owners(self, tenant_id: UUID) -> int:
        stmt = (
            select(func.count())
            .select_from(TenantMembership)
            .where(
                TenantMembership.tenant_id == tenant_id,
                TenantMembership.is_owner.is_(True),
                TenantMembership.status == MembershipStatus.ACTIVE,
            )
        )
        result = await self.session.execute(stmt)
        return int(result.scalar_one())
