from uuid import UUID

from psycopg import Connection
from src.__types.index import Tenant
from src.domain.entities.quota import Quota
from src.domain.entities.quota_allocation import QuotaAllocation, QuotaAllocationStatus
from src.infrastructure.repositories.quota_repository import QuotaRepository
from src.tracer import tracer


class QuotaUseCase:
    def __init__(self, quota_repository: QuotaRepository) -> None:
        self.quota_repository = quota_repository

    @classmethod
    def create(cls, tenant: Tenant, connection: Connection) -> "QuotaUseCase":
        return QuotaUseCase(
            quota_repository=QuotaRepository(tenant=tenant, connection=connection),
        )

    @tracer.capture_method
    def check(self) -> bool:
        """クォータが超過していないか確認する"""
        quota = self.quota_repository.get()
        return not quota.is_exceeded

    def get(self) -> Quota:
        """クォータを取得する"""
        return self.quota_repository.get()

    def get_allocations(self, status: list[QuotaAllocationStatus]) -> tuple[UUID | None, list[QuotaAllocation]]:
        """指定されたステータスのクォータ割り当ておよび使用中のクォータ割り当てIDを取得する"""
        quota = self.quota_repository.get()
        return quota.in_use_allocation_id, [
            allocation for allocation in quota.allocations if allocation.status in status
        ]
