from __future__ import annotations

from canonical_layer.mappers import map_record


def _find_link(entity, source_field: str):
    for link in entity.links:
        if link.source_field == source_field:
            return link
    return None


def test_map_record_keeps_explicit_identity_and_links() -> None:
    row = {
        "Ref_Key": "11111111-2222-3333-4444-555555555555",
        "Description": "Документ тест",
        "Counterparty_Key": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    }
    entity = map_record("DocumentSales", row)

    assert entity.source_id == "11111111-2222-3333-4444-555555555555"
    assert entity.display_name == "Документ тест"

    link = _find_link(entity, "Counterparty_Key")
    assert link is not None
    assert link.target_entity == "Counterparty"
    assert link.relation == "document_has_counterparty"


def test_map_record_builds_composite_source_id_for_registers() -> None:
    row = {
        "Recorder": "12345678-1111-2222-3333-123456789abc",
        "Recorder_Type": "StandardODATA.Document_РеализацияТоваровУслуг",
        "LineNumber": "7",
        "Period": "2020-06-01T00:00:00",
    }
    entity = map_record("AccumulationRegister_НДСЗаписиКнигиПродаж_RecordType", row)

    assert entity.source_id.startswith("cmp:")
    recorder_link = _find_link(entity, "Recorder")
    assert recorder_link is not None
    assert recorder_link.target_entity == "Document"
    assert recorder_link.relation == "register_recorded_by_document"


def test_map_record_journal_ref_points_to_document() -> None:
    row = {
        "Ref": "22222222-3333-4444-5555-666666666666",
        "Ref_Type": "StandardODATA.Document_СписаниеСРасчетногоСчета",
        "Description": "Журнал банковских выписок",
    }
    entity = map_record("DocumentJournal_БанковскиеВыписки", row)

    assert entity.source_id == "22222222-3333-4444-5555-666666666666"
    ref_link = _find_link(entity, "Ref")
    assert ref_link is not None
    assert ref_link.target_entity == "Document"
    assert ref_link.relation == "journal_refers_to_document"


def test_map_record_supplier_and_buyer_are_typed_counterparties() -> None:
    row = {
        "Recorder": "44444444-1111-2222-3333-abcdefabcdef",
        "Recorder_Type": "StandardODATA.Document_ПоступлениеТоваровУслуг",
        "Поставщик_Key": "aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb",
        "Покупатель_Key": "cccccccc-1111-2222-3333-dddddddddddd",
    }
    entity = map_record("AccumulationRegister_НДСПредъявленный_RecordType", row)

    supplier = _find_link(entity, "Поставщик_Key")
    buyer = _find_link(entity, "Покупатель_Key")
    assert supplier is not None
    assert buyer is not None
    assert supplier.target_entity == "Counterparty"
    assert buyer.target_entity == "Counterparty"
    assert supplier.relation == "register_relates_to_supplier"
    assert buyer.relation == "register_relates_to_buyer"


def test_map_record_invoice_not_misclassified_as_account() -> None:
    row = {
        "Recorder": "99999999-1111-2222-3333-eeeeeeeeeeee",
        "Recorder_Type": "StandardODATA.Document_ФормированиеЗаписейКнигиПокупок",
        "СчетФактура": "11111111-aaaa-bbbb-cccc-222222222222",
        "СчетФактура_Type": "StandardODATA.Document_СчетФактураПолученный",
    }
    entity = map_record("AccumulationRegister_НДСЗаписиКнигиПокупок_RecordType", row)

    invoice = _find_link(entity, "СчетФактура")
    assert invoice is not None
    assert invoice.target_entity == "InvoiceDocument"
    assert invoice.relation == "register_relates_to_invoice"


def test_map_record_zero_guid_links_are_filtered_out() -> None:
    row = {
        "Ref_Key": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
        "Counterparty_Key": "00000000-0000-0000-0000-000000000000",
    }
    entity = map_record("Document_РеализацияТоваровУслуг", row)
    assert _find_link(entity, "Counterparty_Key") is None
