from time import time

from aiohttp import ClientResponseError
from fastapi import APIRouter

from app import mongo
from app.providers import tinkoff
from app.utils.response_util import response

router = APIRouter()


@router.post("/create-deal-bill", tags=[""])
async def create_deal_bill(params: dict):
    start_time = time()
    deal_id = params["dealId"]

    deal = await mongo.deals_collection.find_one({
        "id": deal_id
    }, {
        "_id": False
    })

    client = await mongo.clients_collection.find_one({
        "name": deal["clientName"]
    }, {
        "_id": False
    })

    try:
        total_price = await mongo.get_deals_total_prices(deal)
        bill_data = await tinkoff.create_bill(deal_id, total_price[deal_id], client)

        bill_request_data = {
            "invoiceId": bill_data["invoiceId"],
            "pdfUrl": bill_data["pdfUrl"],
            "paid": False
        }

        await mongo.deals_collection.update_one(
            {"id": deal_id},
            {"$set": {"billRequest": bill_request_data}}
        )

        return response({
            "ok": True,
            "message": "Счёт успешно создан"
        }, start_time=start_time)
    except ClientResponseError:
        return response({
            "ok": False,
            "message": "Не получилось создать счёт"
        }, start_time=start_time)


@router.post("/cancel-deal-bill", tags=[""])
async def cancel_deal_bill(params: dict):
    start_time = time()
    deal_id = params["dealId"]

    await mongo.deals_collection.update_one(
        {"id": deal_id},
        {"$set": {"billRequest": None}}
    )

    return response({
        "ok": True,
        "message": "Счёт успешно отозван"
    }, start_time=start_time)
