from time import time

from fastapi import APIRouter

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

router = APIRouter()


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

    deal_id = params["dealId"]
    service_data = {
        "serviceId": params["serviceId"],
        "quantity": params["quantity"],
        "price": params["price"]
    }

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

    services = deal.get("services", [])
    services.append(service_data)

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


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

    deal_id = params["dealId"]
    service_id = params["service"]["serviceId"]

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

    services = deal.get("services", [])
    for service in services:
        if service["serviceId"] == service_id:
            for key, value in params["service"].items():
                service[key] = value
            break

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


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

    deal_id = params["dealId"]
    service_id = params["serviceId"]

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

    services = deal.get("services", [])
    updated_services = [service for service in services if service["serviceId"] != service_id]

    await mongo.deals_collection.update_one({"id": deal_id}, {"$set": {"services": updated_services}})
    return response({
        "message": "Услуга удалена из сделки",
        "ok": True
    }, start_time=start_time)


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

    deal_id = params["dealId"]
    source_product_id = params["sourceProductId"]
    destination_product_ids = params["destinationProductIds"]

    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", [])
    source_product_services = []

    for product in products:
        if product["productId"] == source_product_id:
            source_product_services = product.get("services", [])
            break

    source_services_map = {s["serviceId"]: s for s in source_product_services}
    service_quantities = {}

    for product in products:
        if product["productId"] in destination_product_ids:
            new_services = []
            for service_id, service in source_services_map.items():
                new_service = service.copy()
                new_services.append(new_service)
                service_quantities[service_id] = service_quantities.get(service_id, 0) + product["quantity"]
            product["services"] = new_services

    for service_id, total_quantity in service_quantities.items():
        service_data = await mongo.services_collection.find_one({"id": service_id})
        if not service_data or "priceRanges" not in service_data:
            continue

        price_ranges = sorted(service_data["priceRanges"], key=lambda x: x["fromQuantity"])
        new_price = None

        for price_range in price_ranges:
            if total_quantity >= price_range["fromQuantity"]:
                new_price = price_range["price"]

        if new_price is not None:
            for product in products:
                for service in product.get("services", []):
                    if service["serviceId"] == service_id and not service.get("isFixedPrice", False):
                        service["price"] = new_price

    await mongo.deals_collection.update_one({"id": deal_id}, {"$set": {"products": products}})
    return response({
        "message": "Услуги скопированы и обновлены",
        "ok": True
    }, start_time=start_time)
