"""SuInvoices — Beletage's own invoices (writes to seap.beletage_invoices)."""
from __future__ import annotations

from ..xml_utils import (
    find_child_local, find_local, text_under, text_direct,
    int_under, decimal_under, datetime_under, sysitem_name, to_jsonable,
)


def parse(el) -> dict | None:
    invoice_id = int_under(el, 'InvoiceId')
    if invoice_id is None:
        return None

    # Sums of payments
    paid_value = None
    paid_at = None
    payments = find_local(el, 'Payments')
    if payments is not None:
        for pay in payments:
            v = decimal_under(pay, 'Value')
            d = datetime_under(pay, 'Date')
            if v is not None:
                paid_value = (paid_value or 0) + v
            if d is not None and (paid_at is None or d > paid_at):
                paid_at = d

    return {
        'invoice_id': invoice_id,
        'invoice_no': text_under(el, 'InvoiceNumber') or text_under(el, 'InvoiceNo'),
        'invoice_date': (datetime_under(el, 'InvoiceDate') or datetime_under(el, 'IssueDate')),
        'due_date': datetime_under(el, 'DueDate'),
        'contract_id': int_under(el, 'ContractId'),
        'contract_no': text_under(el, 'ContractNo'),
        'authority_name': text_under(el, 'BuyerName') or text_under(el, 'AuthorityName'),
        'authority_cui': text_under(el, 'BuyerCif') or text_under(el, 'AuthorityCif'),
        'total_value': decimal_under(el, 'TotalValue') or decimal_under(el, 'GrandTotal'),
        'total_value_no_vat': decimal_under(el, 'TotalValueNoVat') or decimal_under(el, 'NetTotal'),
        'vat_value': decimal_under(el, 'VatValue') or decimal_under(el, 'VAT'),
        'currency': sysitem_name(el, 'Currency') or text_under(el, 'CurrencyCode'),
        'state': sysitem_name(el, 'SysInvoiceState') or text_under(el, 'State'),
        'paid_value': paid_value,
        'paid_at': paid_at,
        'details': to_jsonable(el),
    }


def _date_only(dt):
    return dt.date() if dt else None
