"""Tests para generate_service_worker."""

from generate_service_worker import generate_service_worker


def test_default_sw_contains_install_activate_fetch_handlers():
    """SW por defecto contiene install/activate/fetch handlers."""
    code = generate_service_worker()
    assert "addEventListener('install'" in code
    assert "addEventListener('activate'" in code
    assert "addEventListener('fetch'" in code


def test_custom_precache_urls_appear_in_code():
    """Custom precache_urls aparecen en el codigo."""
    urls = ["/", "/index.html", "/manifest.json", "/offline.html"]
    code = generate_service_worker(precache_urls=urls)
    for url in urls:
        assert f"'{url}'" in code


def test_custom_network_first_patterns_appear_in_fetch_handler():
    """Custom network_first_patterns aparecen en el fetch handler."""
    patterns = ["/api/", "/graphql"]
    code = generate_service_worker(network_first_patterns=patterns)
    for pattern in patterns:
        assert f"url.includes('{pattern}')" in code


def test_cache_name_appears_in_code():
    """El cache_name personalizado aparece en el codigo generado."""
    code = generate_service_worker(cache_name="voice-guide-v1")
    assert "voice-guide-v1" in code


def test_default_values_are_used_when_none():
    """Los valores por defecto se usan cuando los parametros son None."""
    code = generate_service_worker()
    assert "'/'" in code
    assert "'/index.html'" in code
    assert "url.includes('/api/')" in code


def test_returns_valid_string():
    """La funcion retorna un string no vacio."""
    code = generate_service_worker()
    assert isinstance(code, str)
    assert len(code) > 0


def test_activate_cleans_old_caches():
    """El evento activate limpia caches antiguos."""
    code = generate_service_worker(cache_name="my-cache-v2")
    assert "caches.keys()" in code
    assert "caches.delete(name)" in code
    assert "name !== CACHE_NAME" in code


def test_cache_first_fallback_saves_to_cache():
    """La estrategia cache-first guarda respuestas de red en cache."""
    code = generate_service_worker()
    assert "cache.put(event.request" in code
