"""

    AUTHOR:

        Khushal P Soonderji

    DATE:

        Saturday, 7th Dec., 2024.

    OBJECTIVE:

        To define how payment transactions will be stored in the database.

    REFERENCES:

        N/A

    DOWNLOADS:

        N/A

"""


#   *****************************************************************************************************************
#  *****                                                                                                          ****
# ***                                                   IMPORT                                                      ***
#  *****                                                                                                          ****
#   *****************************************************************************************************************


# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")

# For making data behaviour_models:
from pydantic import BaseModel, Field, field_validator, PastDatetime, AwareDatetime, model_validator
from typing import Optional, Literal, Union, List, Any

# My utils:
from utils_v2.string import regex
from utils_v2.date_time import date_time

# Other core models:
from models.core.user import CoreUserInfoModel

# To work with MongoDB:
from bson.objectid import ObjectId

# To work with date and time:
import datetime

# To work with currencies:
import pycountry


#   *****************************************************************************************************************
#  *****                                                                                                          ****
# ***                                           MACROS / ONE-TIME INIT                                              ***
#  *****                                                                                                          ****
#   *****************************************************************************************************************


# --- Nothing Yet


#   *****************************************************************************************************************
#  *****                                                                                                          ****
# ***                                                VARIABLES                                                      ***
#  *****                                                                                                          ****
#   *****************************************************************************************************************


# --- Nothing Yet


#   *****************************************************************************************************************
#  *****                                                                                                          ****
# ***                                                  FUNCTIONS                                                    ***
#  *****                                                                                                          ****
#   *****************************************************************************************************************


class CustomerDetails(BaseModel):

    name: str | None = Field(
        description = "the name of the registered customer who must make the payment",
        frozen = True,
        default = None
    )

    contactNo: str = Field(
        description = "the contact no. of the registered customer who must make the payment",
        frozen = True
    )

    payerNo: str | None = Field(
        description = (
            "the phone no. to which the payment request will go;"
            "if not specified, the value of 'contactNo' will be used"
        ),
        frozen = False,
        default = None
    )

    email: str | None = Field(
        description = "the e-mail id of the registered customer",
        pattern = regex.REGEX_EMAIL_ID,
        frozen = True,
        default = None
    )

    # ┏┓    ┏•
    # ┃ ┏┓┏┓╋┓┏┓
    # ┗┛┗┛┛┗┛┗┗┫
    #          ┛

    class Config:
        extra = "allow"
        arbitrary_types_allowed = True

    # ┓┏  ┓• ┓   •
    # ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
    # ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗

    @model_validator(mode = "after")
    def validate_model(cls, values):
        if values.payerNo is None: values.payerNo = values.contactNo
        return values


# ---------------------------------------------------------------------------------------------------------------------


class PaymentEvent(BaseModel):

    eventTs: AwareDatetime = Field(
        description = "to know the date and time (utc) of this update",
        frozen = True,
        default_factory = lambda: date_time.get_current_utc_date_time(as_string = False)
    )

    paymentStatus: Literal[
        "queued",  # ....... When the UI sends a payment request, but the payment gateway (PG) hasn't received it yet.
        "initFailed",  # ... When we tried to initiate the request, but the PG rejected it.
        "initiated",  # .... When we made a successful payment request, or the customer initiated one from the PG.
        "failed",  # ....... When the customer tried paying, but it failed (e.g.: because of an incorrect pin).
        "rejected",  # ..... When the customer explicitly rejected the payment.
        "authorized",  # ... When the customer made the payment (but it hasn't been settled in your account yet).
        "settled",  # ...... When the PG sends the money to your account.
        "refunded",  # ..... When the money was refunded to the client.
        "unknown"  # ....... When integrating a new gateway and some specific status is not known.
    ] = Field(
        description = "the status of the payment request to see what stage of the process we are in",
        frozen = False
    )

    message: str | None = Field(
        description = "a hint about what happened at this stage",
        frozen = True,
        default = None
    )

    initByPG: bool = Field(
        description = "to figure out whether the payment gateway initiated this event or we did",
        frozen = True
    )

    httpCode: int | None = Field(
        description = "the http code generated by the event",
        frozen = True,
        examples = [200, 400, 401]
    )

    headers: dict = Field(
        description = "the headers that came in with the event; useful when trying to decode who generated the event"
    )

    payload: dict = Field(
        description = "the json payload or set of query params received from an event from the payment gateway",
        frozen = True
    )

    # ┏┓    ┏•
    # ┃ ┏┓┏┓╋┓┏┓
    # ┗┛┗┛┛┗┛┗┗┫
    #          ┛

    class Config:
        extra = "allow"
        arbitrary_types_allowed = True

    # ┓┏  ┓• ┓   •
    # ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
    # ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗

    @field_validator("eventTs", mode = "before")
    def parse_date_time(cls, value):
        return date_time.parse_date_time(input_value = value, timezone = date_time.TIMEZONE_UTC)


# ---------------------------------------------------------------------------------------------------------------------


class CorePaymentModel(BaseModel):

    paymentId: ObjectId = Field(
        description = "the id of the document in mongodb that holds this information",
        frozen = True,
        default = None,
        alias = "_id"
    )

    user: CoreUserInfoModel = Field(
        description = "how you identify your user",
        frozen = True
    )

    customer: CustomerDetails = Field(
        description = "how you identify your user's customer",
        frozen = True
    )

    ts: AwareDatetime = Field(
        description = "the time (utc) at which the payment was first initiated",
        frozen = True,
        default_factory = lambda: date_time.get_current_utc_date_time(as_string = False)
    )

    lastEventTs: AwareDatetime | None = Field(
        description = "the time (utc) at which the last event occurred",
        frozen = True,
        default = None
    )

    lastPaymentStatus: str = Field(
        description = "the status of the payment request to see what stage of the process we are in",
        frozen = False
    )

    tokenId: ObjectId = Field(
        description = "the id of the auth token that is associated with this payment",
        frozen = True
    )

    amount: float | int = Field(
        description = "the amount of money being requested",
        frozen = True
    )

    currencyCode: str = Field(
        description = "the three-letter iso 4217 code to identify the currency",
        frozen = True,
        examples = ["INR", "USD", "KES"]
    )

    metadata: dict | None = Field(
        description = "any arbitrary amount of data to identify the user and payment details",
        frozen = True
    )

    tags: List[Any] = Field(
        description = "a list of keywords to apply to this file/dir to filter it later",
        frozen = False,
        examples = ["renewal", "subscription"]
    )

    serviceType: Literal["paymentGateway"] = Field(
        description = "to identify the kind of service",
        frozen = True,
        default = None
    )

    client: Literal["razorpay", "safaricomMPesaExpress"] = Field(
        description = "the third-part client that was used",
        frozen = True
    )

    clientPaymentReferenceId: int | str | None = Field(
        description = "the reference id given by the third-party client",
        frozen = False,
        default = None
    )

    events: List[PaymentEvent] = Field(
        description = "an array of all the events that happened in the process of this payment",
        frozen = False
    )

    # ┏┓    ┏•
    # ┃ ┏┓┏┓╋┓┏┓
    # ┗┛┗┛┛┗┛┗┗┫
    #          ┛

    class Config:
        extra = "allow"
        arbitrary_types_allowed = True

    def model_dump(self, *args, **kwargs):
        return super().model_dump(*args, by_alias = True, **kwargs)

    # ┏┓           •
    # ┃┃┏┓┏┓┏┓┏┓┏┓╋┓┏┓┏
    # ┣┛┛ ┗┛┣┛┗ ┛ ┗┗┗ ┛
    #       ┛

    @property
    def full(self):
        payment_json = {
            "paymentId": str(self.paymentId),
            "user": self.user.model_dump(),
            "customer": self.customer.model_dump(),
            "ts": self.ts.isoformat(),
            "lastEventTs": self.lastEventTs,
            "lastPaymentStatus": self.lastPaymentStatus,
            "amount": self.amount,
            "currencyCode": self.currencyCode,
            "client": self.client,
            "clientPaymentReferenceId": self.clientPaymentReferenceId,
            "tags": self.tags,
            "metadata": self.metadata,
            "events": []
        }
        for e in self.events:
            payment_json["events"].append({
                "eventTs": e.eventTs,
                "paymentStatus": e.paymentStatus,
                "initByPG": e.initByPG
            })
        return payment_json

    @property
    def preview(self):
        return {
            "paymentId": str(self.paymentId),
            "user": self.user.model_dump(),
            "customer": self.customer.model_dump(),
            "ts": self.ts.isoformat(),
            "lastEventTs": self.lastEventTs,
            "lastPaymentStatus": self.lastPaymentStatus,
            "amount": self.amount,
            "currencyCode": self.currencyCode,
            "client": self.client,
            "clientPaymentReferenceId": self.clientPaymentReferenceId,
            "tags": self.tags,
            "metadata": self.metadata
        }

    # ┓┏  ┓• ┓   •
    # ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
    # ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗

    @field_validator("ts", "lastEventTs", mode = "before")
    def parse_date_time(cls, value):
        return date_time.parse_date_time(input_value = value, timezone = date_time.TIMEZONE_UTC)

    @field_validator("tokenId", mode = "before")
    def parse_oid(cls, value):
        try:
            if isinstance(value, str):
                value = ObjectId(value)
        except: pass
        return value

    @field_validator("currencyCode", mode = "before")
    def validate_currency(cls, value):
        currency = pycountry.currencies.get(alpha_3 = value)
        if currency is None: raise ValueError("invalid currency code, please use iso 4217 standard")
        return value

    @field_validator("tags", "events", mode = "before")
    def validate_null_lists(cls, value):
        if value is None: value = []
        return value


#   *****************************************************************************************************************
#  *****                                                                                                          ****
# ***                                               MAIN PROGRAM                                                    ***
#  *****                                                                                                          ****
#   *****************************************************************************************************************


if __name__ == "__main__":

    from utils_v2.string import json

    now = date_time.get_current_utc_date_time(as_string = False)

    payment = CorePaymentModel(
        tokenId = "67519cf3a7804fcbc6f12452",
        user = CoreUserInfoModel(
            userId = 1
        ),
        customer = CustomerDetails(
            name = "Bhopli Narangi",
            contactNo = "9876543210",
            email = "bhopli@orange.com"
        ),
        amount = 1.00,
        currencyCode = "INR",
        metadata = {
            "key": "value"
        },
        tags = [
            "some",
            "tags"
        ],
        client = "razorpay",
        clientPaymentReferenceId = "txn_123_abc",
        lastPaymentStatus = "settled",
        lastEventTs = now,
        events = [
            PaymentEvent(
                eventTs = now - datetime.timedelta(minutes = 1, seconds = 12),
                paymentStatus = "initiated",
                initByPG = False,
                httpCode = None,
                headers = {
                    "some": "header"
                },
                payload = {
                    "status": "captured",
                    "from": "Barfi",
                }
            ),
            PaymentEvent(
                eventTs = now,
                paymentStatus = "settled",
                initByPG = True,
                httpCode = None,
                headers = {
                    "some": "header"
                },
                payload = {
                    "status": "authorized",
                    "from": "Barfi",
                    "amount": -100.00,
                    "description": "meow"
                }
            )
        ]
    )

    print("PAYMENT TXN. MODEL:", json.to_string(payment.model_dump(), default = str))
