from datetime import datetime
from typing import List

from maps_adv.stat_tasks_starter.lib.charger.clients.base import BaseClient

from .schemas import (
    ReceiveOrdersInputSchema,
    ReceiveOrdersOutputSchema,
    SubmitOrdersChargesInputSchema,
    SubmitOrdersChargesOutputSchema,
)


class BillingClient(BaseClient):
    async def receive_orders(self, order_list: list) -> List[dict]:
        data = ReceiveOrdersInputSchema().to_bytes({"order_ids": order_list})

        got = await self._request("POST", "/orders/stats/", 200, data=data)

        return ReceiveOrdersOutputSchema().from_bytes(got)["orders_info"]

    async def submit_charges(self, charges: List[dict], bill_for_timestamp: datetime):
        data = SubmitOrdersChargesInputSchema().to_bytes(
            {"orders_charge": charges, "bill_for_timestamp": bill_for_timestamp}
        )
        got = await self._request("POST", "/orders/charge/", 201, data=data)

        charge_result = SubmitOrdersChargesOutputSchema().from_bytes(got)[
            "charge_result"
        ]
        return {i["order_id"]: i["success"] for i in charge_result}
