from time import time

from fastapi import APIRouter

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

router = APIRouter()


@router.get("/available/{user_id}", tags=[""])
async def get(user_id: int):
    start_time = time()

    employees = await mongo.users_collection.find({}, {
        "_id": False
    }).sort("id", mongo.asc).to_list()

    return response({
        "employees": employees
    }, start_time=start_time)


@router.post("", tags=[""])
async def add(params: dict):
    start_time = time()
    params["createdAt"] = mongo.created_at()

    deal = await mongo.deals_collection.find_one(
        {"id": params["dealId"]},
        {"_id": False}
    )

    employees = deal.get("employees", [])
    user_entry = {"userId": params["userId"], "createdAt": params["createdAt"]}

    if params["isAssign"]:
        if user_entry not in employees:
            employees.append(user_entry)
    else:
        employees = [employee for employee in employees if employee["userId"] != params["userId"]]

    await mongo.deals_collection.update_one(
        {"id": params["dealId"]},
        {"$set": {"employees": employees}}
    )

    return response({
        "message": "Данные обновлены",
        "ok": True
    }, start_time=start_time)