"""Tests para enum_subdomains_crtsh."""

import os
import sys

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

import enum_subdomains_crtsh as esc
from enum_subdomains_crtsh import enum_subdomains_crtsh


def _crtsh_sample() -> list:
    # crt.sh devuelve un array; name_value puede traer varios SAN separados
    # por '\n', con duplicados y wildcards.
    return [
        {"name_value": "www.organic-machine.com\norganic-machine.com"},
        {"name_value": "api.organic-machine.com"},
        {"name_value": "www.organic-machine.com"},  # duplicado
        {"name_value": "*.organic-machine.com"},  # wildcard, se filtra
        {"name_value": "MAIL.Organic-Machine.com"},  # case distinto
    ]


def test_dedup_y_orden(monkeypatch):
    """Subdominios deduplicados, en minusculas y ordenados."""
    monkeypatch.setattr(
        esc, "http_get_json", lambda url, timeout=20.0: _crtsh_sample()
    )

    result = enum_subdomains_crtsh("organic-machine.com")

    assert result == [
        "api.organic-machine.com",
        "mail.organic-machine.com",
        "organic-machine.com",
        "www.organic-machine.com",
    ]


def test_filtra_wildcards(monkeypatch):
    """Las entradas '*.dominio' se descartan."""
    monkeypatch.setattr(
        esc,
        "http_get_json",
        lambda url, timeout=20.0: [{"name_value": "*.organic-machine.com"}],
    )

    result = enum_subdomains_crtsh("organic-machine.com")

    assert result == []


def test_respuesta_vacia(monkeypatch):
    """crt.sh sin resultados devuelve lista vacia."""
    monkeypatch.setattr(esc, "http_get_json", lambda url, timeout=20.0: [])

    result = enum_subdomains_crtsh("organic-machine.com")

    assert result == []


def test_respuesta_no_lista_lanza_error(monkeypatch):
    """Una respuesta que no es lista lanza RuntimeError."""
    monkeypatch.setattr(
        esc, "http_get_json", lambda url, timeout=20.0: {"unexpected": "obj"}
    )

    try:
        enum_subdomains_crtsh("organic-machine.com")
        assert False, "deberia haber lanzado RuntimeError"
    except RuntimeError:
        pass


def test_dominio_vacio_lanza_error():
    """Dominio vacio lanza RuntimeError."""
    try:
        enum_subdomains_crtsh("")
        assert False, "deberia haber lanzado RuntimeError"
    except RuntimeError:
        pass
