import pytest
import aiohttp
from unittest.mock import patch, AsyncMock, MagicMock
from cve_checker.cve_data_fetcher import CVEDataFetcher

class AsyncContextManagerMock:
    def __init__(self, return_value):
        self.return_value = return_value

    async def __aenter__(self):
        return self.return_value

    async def __aexit__(self, exc_type, exc, tb):
        pass

@pytest.fixture
def cve_data_fetcher():
    return CVEDataFetcher()

@pytest.mark.asyncio
async def test_fetch_cve_data(cve_data_fetcher):
    mock_response = {
        'result': {
            'CVE_Items': [
                {'cve': {'CVE_data_meta': {'ID': 'CVE-2021-1234'}}},
                {'cve': {'CVE_data_meta': {'ID': 'CVE-2021-5678'}}}
            ]
        }
    }
    
    mock_response_obj = AsyncMock()
    mock_response_obj.json.return_value = mock_response
    mock_response_obj.raise_for_status = MagicMock()  # Change this to MagicMock

    mock_session = AsyncMock()
    mock_session.get = MagicMock(return_value=AsyncContextManagerMock(mock_response_obj))

    mock_client_session = AsyncContextManagerMock(mock_session)

    with patch('aiohttp.ClientSession', return_value=mock_client_session):
        with patch.object(cve_data_fetcher, '_is_cache_valid', return_value=False):
            with patch.object(cve_data_fetcher, '_cache_data'):
                result = await cve_data_fetcher.fetch_cve_data()
        
                assert len(result) == 2
                assert result[0]['cve']['CVE_data_meta']['ID'] == 'CVE-2021-1234'
                assert result[1]['cve']['CVE_data_meta']['ID'] == 'CVE-2021-5678'

def test_is_cache_valid(cve_data_fetcher, tmp_path):
    cve_data_fetcher.cache_file = tmp_path / "test_cache.json"
    
    # Test with no cache file
    assert not cve_data_fetcher._is_cache_valid()
    
    # Test with a fresh cache file
    cve_data_fetcher.cache_file.touch()
    assert cve_data_fetcher._is_cache_valid()

def test_load_cache(cve_data_fetcher, tmp_path):
    cve_data_fetcher.cache_file = tmp_path / "test_cache.json"
    test_data = [{'cve': {'CVE_data_meta': {'ID': 'CVE-2021-1234'}}}]
    
    cve_data_fetcher._cache_data(test_data)
    loaded_data = cve_data_fetcher._load_cache()
    
    assert loaded_data == test_data
