from posot import OrderTaker
from typing import Optional

from open_loyalty import get_document_from_loyalty_or_customer_response
from utilfunctions import (
    fill_additional_info,
    get_custom_property_value,
)


def get_loyalty_document(
    pos_id,                 # type: str
    pos_ot,                 # type: OrderTaker
    ask_document_pinpad,    # type: bool
):
    # type: (...) -> Optional[str]

    loyalty_customer_info = get_custom_property_value(
        pos_id=pos_id,
        custom_property='LOYALTY_CUSTOMER_INFO',
    )

    if loyalty_customer_info is not None:
        document = get_custom_property_value(
            pos_id=pos_id,
            custom_property='CUSTOMER_DOC',
        )
        return document or ""

    loyalty_document = get_document_from_loyalty_or_customer_response(
        pos_id=pos_id,
        pos_ot=pos_ot,
        ask_document_pinpad=ask_document_pinpad,
    )
    if loyalty_document is None:
        return None

    document = loyalty_document
    fill_additional_info(
        pos_ot=pos_ot,
        properties="CPF",
        value=document,
    )

    return document
