"""Test the system settings service integration."""
import pytest

from src.server.database.connection import get_db_session, init_db
from src.server.database.system_settings_service import SystemSettingsService


@pytest.mark.asyncio
async def test_system_settings_integration():
    """Test SystemSettings service with actual database operations."""
    # Initialize database
    await init_db()

    # Reset all flags to a known-clean state before the test
    async with get_db_session() as db:
        await SystemSettingsService.reset_all_scans(db)

    # Test get_or_create (should return record with all flags False after reset)
    async with get_db_session() as db:
        settings = await SystemSettingsService.get_or_create(db)
        assert settings is not None
        assert settings.id is not None
        assert settings.initial_scan_completed is False
        assert settings.initial_nfo_scan_completed is False
        assert settings.initial_media_scan_completed is False
        assert settings.migration_legacy_files_completed is False
        assert settings.legacy_key_cleanup_completed is False
        
    # Test checking individual flags
    async with get_db_session() as db:
        is_scan_done = await SystemSettingsService.is_initial_scan_completed(db)
        assert is_scan_done is False
        
        is_nfo_done = await SystemSettingsService.is_initial_nfo_scan_completed(db)
        assert is_nfo_done is False
        
        is_media_done = await SystemSettingsService.is_initial_media_scan_completed(db)
        assert is_media_done is False
        
        is_migration_done = await SystemSettingsService.is_migration_legacy_files_completed(db)
        assert is_migration_done is False
        
        is_key_cleanup_done = await SystemSettingsService.is_legacy_key_cleanup_completed(db)
        assert is_key_cleanup_done is False
    
    # Test marking scans as completed
    async with get_db_session() as db:
        await SystemSettingsService.mark_initial_scan_completed(db)
        
    async with get_db_session() as db:
        is_scan_done = await SystemSettingsService.is_initial_scan_completed(db)
        assert is_scan_done is True
        
        # Others should still be False
        is_nfo_done = await SystemSettingsService.is_initial_nfo_scan_completed(db)
        assert is_nfo_done is False
    
    # Test reset
    async with get_db_session() as db:
        await SystemSettingsService.reset_all_scans(db)
        
    async with get_db_session() as db:
        settings = await SystemSettingsService.get_or_create(db)
        assert settings.initial_scan_completed is False
        assert settings.initial_nfo_scan_completed is False
        assert settings.initial_media_scan_completed is False
        assert settings.migration_legacy_files_completed is False
        assert settings.legacy_key_cleanup_completed is False


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
