import uuid

from src.__types.index import GroupBy
from src.domain.entities.quota_allocation import QuotaAllocationStatus
from src.infrastructure.repositories.quota_usage_aggregate_query_builder import QuotaUsageAggregateQueryBuilder


class TestQuotaUsageAggregateQueryBuilder:
    def test_build_without_status_skips_quota_allocations_join(self) -> None:
        """Status 未指定時は quota_allocations join を行わないことを確認する"""
        # Arrange
        builder = QuotaUsageAggregateQueryBuilder(
            tenant_id=uuid.uuid4(),
            status=[],
            group_by=[GroupBy.MONTH, GroupBy.SERVICE],
            year=2026,
        )

        # Act
        query, parameters = builder.build()
        query_str = query.as_string(None)

        # Assert
        assert 'FROM "quota_usages" AS qu' in query_str
        assert "qu.quota_allocation_id IS NOT NULL" in query_str
        assert 'INNER JOIN "quota_allocations" AS qa' not in query_str
        assert "qu.tenant_id = %(tenant_id)s" in query_str
        assert "status" not in parameters

    def test_build_with_status_keeps_quota_allocations_join(self) -> None:
        """Status 指定時は quota_allocations join を維持することを確認する"""
        # Arrange
        builder = QuotaUsageAggregateQueryBuilder(
            tenant_id=uuid.uuid4(),
            status=[QuotaAllocationStatus.ACTIVE],
            group_by=[GroupBy.SERVICE],
        )

        # Act
        query, parameters = builder.build()
        query_str = query.as_string(None)

        # Assert
        assert 'INNER JOIN "quota_allocations" AS qa' in query_str
        assert query_str.index('INNER JOIN "quota_allocations" AS qa') < query_str.index("WHERE")
        assert "qa.status = ANY(%(status)s)" in query_str
        assert parameters["status"] == [QuotaAllocationStatus.ACTIVE.value]
