from app.operations_service import _sanitize_operation_identities
from app.admin_ui.view_models.operations import operation_card_title


def test_reused_chatwoot_sender_name_does_not_become_workbench_title():
    items = [
        {
            "source": "task",
            "customer_name": "Alexandre Ruivo",
            "contact_display_name": "Alexandre Ruivo",
            "sender_name": "Alexandre Ruivo",
            "sender_email": "soferreiras@gmail.com",
            "opportunity_title": "Re: Carregadores de última geração para a SÓ FERREIRAS",
            "fiscal_customer_name": "",
        },
        {
            "source": "task",
            "customer_name": "Alexandre Ruivo",
            "contact_display_name": "Alexandre Ruivo",
            "sender_name": "Alexandre Ruivo",
            "sender_email": "geral@novamaquiambiente.pt",
            "opportunity_title": "Re: Carregadores de última geração para a Nova Maquiambiente",
            "fiscal_customer_name": "",
        },
    ]

    fixed = _sanitize_operation_identities(items)

    assert fixed[0]["contact_identity_status"] == "unsafe"
    assert fixed[0]["contact_display_name"] == ""
    assert operation_card_title(fixed[0]) == "SÓ FERREIRAS"
    assert operation_card_title(fixed[1]) == "Nova Maquiambiente"
    assert "Alexandre Ruivo" not in {operation_card_title(item) for item in fixed}


def test_email_supported_person_name_can_still_be_displayed():
    items = [
        {
            "source": "task",
            "customer_name": "Luis Rocha",
            "contact_display_name": "Luis Rocha",
            "sender_name": "Luis Rocha",
            "sender_email": "luis.rocha@coimpack.pt",
            "opportunity_title": "Sem oportunidade comercial",
            "fiscal_customer_name": "",
        }
    ]

    fixed = _sanitize_operation_identities(items)

    assert fixed[0]["contact_identity_status"] == "trusted"
    assert operation_card_title(fixed[0]) == "Luis Rocha"


def test_fiscal_customer_keeps_priority_over_sender_name():
    items = [
        {
            "source": "task",
            "customer_name": "Pessoa Errada",
            "contact_display_name": "Pessoa Errada",
            "sender_name": "Pessoa Errada",
            "sender_email": "geral@example.com",
            "opportunity_title": "Re: Carregadores de última geração para a Empresa X",
            "fiscal_customer_name": "EMPRESA FISCAL, LDA",
        }
    ]

    fixed = _sanitize_operation_identities(items)

    assert fixed[0]["contact_identity_status"] == "fiscal_customer"
    assert operation_card_title(fixed[0]) == "EMPRESA FISCAL, LDA"
