"""Tests para gsc_list_sites (sin red ni credenciales — gsc_auth mockeado)."""

import sys
import os
from unittest.mock import MagicMock, patch

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from infra.gsc_list_sites import gsc_list_sites


def _service_returning(response: dict) -> MagicMock:
    """Construye un service mock cuyo .sites().list().execute() retorna response."""
    service = MagicMock()
    service.sites.return_value.list.return_value.execute.return_value = response
    return service


def test_aplana_siteurl_y_permissionlevel():
    fake = {
        "siteEntry": [
            {"siteUrl": "sc-domain:ejemplo.com", "permissionLevel": "siteOwner"},
            {"siteUrl": "https://www.ejemplo.com/", "permissionLevel": "siteFullUser"},
        ]
    }
    service = _service_returning(fake)
    # La funcion hace `from infra import gsc_auth` en runtime, asi que el
    # simbolo a parchear es infra.gsc_auth (donde se resuelve el lookup).
    with patch("infra.gsc_auth", return_value=service) as mock_auth:
        result = gsc_list_sites()

    mock_auth.assert_called_once_with("")
    assert result == [
        {"site_url": "sc-domain:ejemplo.com", "permission_level": "siteOwner"},
        {"site_url": "https://www.ejemplo.com/", "permission_level": "siteFullUser"},
    ]


def test_site_entry_ausente_devuelve_lista_vacia():
    service = _service_returning({})  # sin clave siteEntry
    with patch("infra.gsc_auth", return_value=service):
        result = gsc_list_sites()

    assert result == []
