from time import time

from fastapi import APIRouter

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

router = APIRouter()


@router.post("/update")
async def update_product(params: dict):
    start_time = time()

    deal_id = params["dealId"]
    product_id = params["product"]["productId"]
    quantity = params["product"]["quantity"]
    services = params["product"]["services"] = [
        {"serviceId": service["service"]["id"], "price": service["price"], "isFixedPrice": service.get("isFixedPrice", False), "quantity": 1}
        for service in params["product"]["services"]
    ]

    deal = await mongo.deals_collection.find_one({"id": deal_id})
    if not deal:
        return response({"message": "Сделка не найдена", "ok": False}, start_time=start_time)

    products = deal.get("products", [])
    for product in products:
        if product["productId"] == product_id:
            if "comment" in params["product"]:
                product["comment"] = params["product"]["comment"]

            product["quantity"] = quantity
            product["services"] = services
            break

    await mongo.deals_collection.update_one({"id": deal_id}, {"$set": {"products": products}})
    return response({
        "message": "Товар обновлён в сделке",
        "ok": True
    }, start_time=start_time)


@router.post("/add-kit")
async def add_kits(params: dict):
    start_time = time()
    deal_id = params["dealId"]
    kit_id = params["kitId"]
    product_id = params["productId"]

    deal = await mongo.deals_collection.find_one({"id": deal_id})
    if not deal:
        return response({"message": "Сделка не найдена", "ok": False}, start_time=start_time)

    service_kit = await mongo.service_kits_collection.find_one({"id": kit_id})
    if not service_kit:
        return response({"message": "Комплект не найден", "ok": False}, start_time=start_time)

    kit_services = []
    for service in service_kit.get("services", []):
        price = service.get("price", 0)
        if service.get("priceRanges"):
            price_range = service["priceRanges"][0]
            price = price_range.get("price", price)

        kit_services.append({
            "serviceId": service["id"],
            "price": price,
            "isFixedPrice": False,
            "quantity": 1
        })

    for product in deal.get("products", []):
        if product["productId"] == product_id:
            product["services"].extend(kit_services)
            break

    await mongo.deals_collection.update_one({"id": deal_id}, {"$set": {"products": deal["products"]}})
    return response({
        "message": "Сервисы из комплекта добавлены в продукт сделки",
        "ok": True
    }, start_time=start_time)