"""Tests para to_csv."""

from to_csv import to_csv


def test_lista_simple_csv_con_header():
    rows = [{"nombre": "Ana", "edad": 30}, {"nombre": "Bob", "edad": 25}]
    result = to_csv(rows)
    lines = result.split("\r\n")
    assert lines[0] == "nombre,edad"
    assert lines[1] == "Ana,30"
    assert lines[2] == "Bob,25"


def test_campos_con_comas_comillas_newlines():
    rows = [{"a": 'dijo "hola"', "b": "uno,dos", "c": "linea1\nlinea2"}]
    result = to_csv(rows)
    lines = result.split("\r\n")
    assert '"dijo ""hola"""' in lines[1]
    assert '"uno,dos"' in lines[1]
    assert '"linea1\nlinea2"' in lines[1]


def test_columns_explicitas_reordena_y_filtra():
    rows = [{"a": 1, "b": 2, "c": 3}]
    result = to_csv(rows, columns=["c", "a"])
    lines = result.split("\r\n")
    assert lines[0] == "c,a"
    assert lines[1] == "3,1"


def test_include_header_false():
    rows = [{"x": "foo", "y": "bar"}]
    result = to_csv(rows, include_header=False)
    lines = result.split("\r\n")
    assert len(lines) == 1
    assert lines[0] == "foo,bar"


def test_lista_vacia_retorna_string_vacio():
    assert to_csv([]) == ""


def test_valores_none_campo_vacio():
    rows = [{"a": "ok", "b": None}]
    result = to_csv(rows)
    lines = result.split("\r\n")
    assert lines[1] == "ok,"
