"""Additional tests for app.core.plans — CheckQuota quota exceeded path"""

import pytest
from unittest.mock import AsyncMock, MagicMock
from app.core.tenant_context import tenant_ctx


@pytest.mark.asyncio
async def test_check_quota_no_tenant():
    """CheckQuota with no tenant context returns True"""
    from app.core.plans import CheckQuota
    checker = CheckQuota("max_saved_items")
    token = tenant_ctx.set(None)
    try:
        result = await checker(db=AsyncMock())
    finally:
        tenant_ctx.reset(token)
    assert result is True


@pytest.mark.asyncio
async def test_check_quota_quota_exceeded():
    """CheckQuota raises 429 when quota exceeded"""
    from app.core.plans import CheckQuota
    from fastapi import HTTPException
    checker = CheckQuota("max_saved_items")
    mock_db = AsyncMock()
    mock_scalar = MagicMock()
    # The first call returns plan_type, second returns count
    mock_scalar.scalar.side_effect = ["free", 300]  # Free limit is 200
    mock_db.execute.return_value = mock_scalar
    token = tenant_ctx.set("00000000-0000-0000-0000-000000000001")
    try:
        with pytest.raises(HTTPException) as exc:
            await checker(db=mock_db)
        assert exc.value.status_code == 429
    finally:
        tenant_ctx.reset(token)


@pytest.mark.asyncio
async def test_check_quota_under_limit():
    """CheckQuota returns True when under limit"""
    from app.core.plans import CheckQuota
    checker = CheckQuota("max_saved_items")
    mock_db = AsyncMock()
    mock_scalar = MagicMock()
    mock_scalar.scalar.side_effect = ["free", 50]  # Free limit is 200
    mock_db.execute.return_value = mock_scalar
    token = tenant_ctx.set("00000000-0000-0000-0000-000000000001")
    try:
        result = await checker(db=mock_db)
        assert result is True
    finally:
        tenant_ctx.reset(token)
