from time import time

from fastapi import APIRouter
from starlette.requests import Request

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

router = APIRouter()


@router.get("", tags=[""])
async def get(full: bool):
    start_time = time()

    return response({
        "summaries": await mongo.get_all_summaries(full)
    }, start_time=start_time)


@router.post("/reorder", tags=[""])
async def reorder(params: dict, request: Request):
    start_time = time()

    deal_id = params["dealId"]
    status_id = params["statusId"]
    index = params["index"]
    comment = params["comment"]

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

    update_fields = {
        "statusId": status_id,
        "index": index
    }

    new_status = await mongo.statuses_collection.find_one({"id": status_id}, {"_id": False})
    if new_status and new_status.get("name") == "Завершено":
        update_fields["completedAt"] = mongo.created_at()

    old_status_id = deal.get("statusId")
    await mongo.deals_collection.update_one(
        {"id": deal_id},
        {"$set": update_fields}
    )

    if old_status_id != status_id:
        new_entry = {
            "changedAt": mongo.created_at(),
            "fromStatusId": old_status_id,
            "toStatusId": status_id,
            "userId": request.state.user["id"],
            "comment": comment
        }

        await mongo.deals_collection.update_one(
            {"id": deal_id},
            {"$push": {"statusHistory": new_entry}}
        )

    return response({
        "ok": True,
        "summaries": await mongo.get_all_summaries(False)
    }, start_time=start_time)
