"""Tests para join_by_key."""

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

from join_by_key import join_by_key


def test_inner_join_solo_matches():
    """Inner join solo matches."""
    left = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
    right = [{"id": 1, "dept": "eng"}, {"id": 3, "dept": "sales"}]
    result = join_by_key(left, right, key="id", how="inner")
    assert len(result) == 1
    assert result[0]["id"] == 1
    assert result[0]["name"] == "Alice"
    assert result[0]["dept"] == "eng"


def test_left_join_todos_los_left_con_none_para_right_sin_match():
    """Left join todos los left con None para right sin match."""
    left = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
    right = [{"id": 1, "dept": "eng"}]
    result = join_by_key(left, right, key="id", how="left")
    assert len(result) == 2
    alice = next(r for r in result if r["id"] == 1)
    bob = next(r for r in result if r["id"] == 2)
    assert alice["dept"] == "eng"
    assert bob["dept"] is None


def test_right_join():
    """Right join."""
    left = [{"id": 1, "name": "Alice"}]
    right = [{"id": 1, "dept": "eng"}, {"id": 2, "dept": "sales"}]
    result = join_by_key(left, right, key="id", how="right")
    assert len(result) == 2
    eng = next(r for r in result if r["id"] == 1)
    sales = next(r for r in result if r["id"] == 2)
    assert eng["name"] == "Alice"
    assert sales.get("name") is None


def test_outer_join():
    """Outer join."""
    left = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
    right = [{"id": 1, "dept": "eng"}, {"id": 3, "dept": "sales"}]
    result = join_by_key(left, right, key="id", how="outer")
    ids = {r["id"] for r in result}
    assert ids == {1, 2, 3}


def test_campos_duplicados_con_sufijo_right():
    """Campos duplicados con sufijo _right."""
    left = [{"id": 1, "name": "Alice", "score": 90}]
    right = [{"id": 1, "score": 85, "dept": "eng"}]
    result = join_by_key(left, right, key="id", how="inner")
    assert len(result) == 1
    assert result[0]["score"] == 90
    assert result[0]["score_right"] == 85
    assert result[0]["dept"] == "eng"


def test_key_ausente_en_alguna_fila():
    """Key ausente en alguna fila."""
    left = [{"id": 1, "name": "Alice"}, {"name": "Bob"}]  # Bob sin id
    right = [{"id": 1, "dept": "eng"}]
    result = join_by_key(left, right, key="id", how="inner")
    # Solo Alice matchea
    assert len(result) == 1
    assert result[0]["name"] == "Alice"
