from datetime import timedelta, date
from typing import Optional

from aiohttp import ClientSession
from async_lru import alru_cache

TBANK_API_KEY = "t.DO5YeYvZhzf9mylRnFEdlUswA4mv1QX63HM2gj4ojHDcJgwVeY6u6R5Mc4ZnR-Qk6w7z2BPDUjnfg3ZuQAcaxQ"
HEADERS = {
    "Authorization": f"Bearer {TBANK_API_KEY}",
    "Content-Type": "application/json"
}

BASE_URL = "https://business.tbank.ru/openapi/api/v1"


async def create_bill(deal_id: int, total_price: float, client: Optional[dict]) -> dict:
    url = f"{BASE_URL}/invoice/send"
    data = {
        "invoiceNumber": str(deal_id),
        "dueDate": (date.today() + timedelta(days=7)).isoformat(),
        "items": [
            {
                "name": f"Оказание услуг фулфилмента (упаковка товара) и логистических услуг до маркетплейсов. Сделка ID {deal_id}",
                "price": total_price,
                "unit": "-",
                "vat": "None",
                "amount": 1
            }
        ]
    }

    if client:
        data["payer"] = {
            "name": client["companyName"],
            "inn": client["details"]["inn"]
        }

    async with ClientSession(headers=HEADERS) as session:
        async with session.post(url, json=data) as response:
            print(await response.text())

            response.raise_for_status()
            return await response.json()


@alru_cache(ttl=60)
async def get_bill_status(bill_id: str) -> str:
    url = f"{BASE_URL}/openapi/invoice/{bill_id}/info"

    async with ClientSession(headers=HEADERS) as session:
        async with session.get(url) as response:
            response.raise_for_status()
            data = await response.json()
            return data["status"]


