from datetime import datetime
from decimal import Decimal
from typing import List

from maps_adv.stat_tasks_starter.lib.charger.clients.billing import BillingClient


class BillingCharger:
    def __init__(self, billing_url: str):
        self.billing_url = billing_url

    async def __call__(self, orders: List[dict], bill_for_timestamp: datetime) -> None:
        if not orders:
            return

        charges = self._extract_charges(orders)
        submit_result = {}
        if charges:
            submit_result = await self._submit_charges(charges, bill_for_timestamp)

        for order in orders:
            billing_success = None
            if (
                order["amount_to_bill"] != Decimal("0")
                and order["order_id"] is not None
            ):
                billing_success = submit_result[order["order_id"]]
            order["billing_success"] = billing_success

    @staticmethod
    def _extract_charges(charges):
        return [
            {"order_id": c["order_id"], "charged_amount": c["amount_to_bill"]}
            for c in charges
            if c["order_id"] is not None and c["amount_to_bill"] != Decimal("0")
        ]

    async def _submit_charges(self, charges: List[dict], bill_for_timestamp: datetime):
        async with BillingClient(self.billing_url) as billing_client:
            return await billing_client.submit_charges(charges, bill_for_timestamp)
