"""Tests para dns_records."""

import os
import subprocess
import sys

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

from dns_records import dns_records


class _FakeProc:
    def __init__(self, stdout: str):
        self.stdout = stdout
        self.returncode = 0


def test_parsea_salida_de_dig(monkeypatch):
    """Cada linea no vacia de dig se convierte en un valor del registro."""
    fixtures = {
        "A": "135.125.201.30\n",
        "MX": "10 mail.organic-machine.com.\n20 mail2.organic-machine.com.\n",
        "TXT": '"v=spf1 -all"\n',
    }

    def fake_run(cmd, **kwargs):
        # cmd = ["dig", "+short", domain, TYPE]
        record_type = cmd[3]
        return _FakeProc(fixtures.get(record_type, ""))

    monkeypatch.setattr(subprocess, "run", fake_run)

    res = dns_records("organic-machine.com", record_types=["A", "MX", "TXT"])

    assert res["status"] == "ok"
    assert res["domain"] == "organic-machine.com"
    assert res["records"]["A"] == ["135.125.201.30"]
    assert res["records"]["MX"] == [
        "10 mail.organic-machine.com.",
        "20 mail2.organic-machine.com.",
    ]
    assert res["records"]["TXT"] == ['"v=spf1 -all"']
    assert "=== A ===" in res["raw"]
    assert "=== MX ===" in res["raw"]


def test_dominio_inexistente_listas_vacias(monkeypatch):
    """Salida vacia de dig (dominio inexistente) produce listas vacias, status ok."""

    def fake_run(cmd, **kwargs):
        return _FakeProc("")

    monkeypatch.setattr(subprocess, "run", fake_run)

    res = dns_records("nope-no-existe-xyz.invalid", record_types=["A", "AAAA"])

    assert res["status"] == "ok"
    assert res["records"] == {"A": [], "AAAA": []}
    assert "(sin registros)" in res["raw"]


def test_usa_tipos_default(monkeypatch):
    """Sin record_types consulta los 7 tipos por defecto."""
    consultados = []

    def fake_run(cmd, **kwargs):
        consultados.append(cmd[3])
        return _FakeProc("")

    monkeypatch.setattr(subprocess, "run", fake_run)

    res = dns_records("organic-machine.com")

    assert res["status"] == "ok"
    assert set(res["records"].keys()) == {"A", "AAAA", "MX", "NS", "SOA", "TXT", "CNAME"}
    assert consultados == ["A", "AAAA", "MX", "NS", "SOA", "TXT", "CNAME"]


def test_timeout_devuelve_lista_vacia(monkeypatch):
    """Un timeout en una consulta deja lista vacia y no aborta el resto."""

    def fake_run(cmd, **kwargs):
        raise subprocess.TimeoutExpired(cmd, 10.0)

    monkeypatch.setattr(subprocess, "run", fake_run)

    res = dns_records("organic-machine.com", record_types=["A"])

    assert res["status"] == "ok"
    assert res["records"] == {"A": []}
    assert "(timeout)" in res["raw"]


def test_dominio_vacio_status_error():
    """Dominio vacio devuelve status error sin lanzar."""
    res = dns_records("")
    assert res["status"] == "error"
    assert res["raw"] == ""
    assert "domain" in res["error"]
