from time import time

from fastapi import APIRouter

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

router = APIRouter()


@router.post("/get", tags=[""])
async def get(data: dict):
    start_time = time()
    client_id = data["clientId"]

    marketplaces = await mongo.marketplaces_collection.find({
        "client.id": client_id
    }, {
        "_id": False
    }).to_list()

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


@router.get("/base/get-all", tags=[""])
async def base_get_all():
    start_time = time()

    baseMarketplaces = await mongo.base_marketplaces_collection.find({}, {
        "_id": False
    }).to_list()

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


@router.post("/create", tags=[""])
async def create(params: dict):
    start_time = time()
    data = params["marketplace"]
    data["id"] = await mongo.get_next_id(mongo.marketplaces_collection)

    await mongo.marketplaces_collection.insert_one(data)
    return response({
        "message": "Маркетплейс клиента создан",
        "ok": True
    }, start_time=start_time)


@router.post("/update", tags=[""])
async def update(params: dict):
    start_time = time()
    data = params["marketplace"]

    try:
        await mongo.marketplaces_collection.update_one({
            "id": data["id"]
        }, {
            "$set": data
        })

        return response({
            "message": "Данные маркетплейса клиента обновлены",
            "ok": True
        }, start_time=start_time)
    except Exception as e:
        return response({
            "message": str(e),
            "ok": False
        }, start_time=start_time, code=400)


@router.post("/delete", tags=[""])
async def delete(params: dict):
    start_time = time()
    marketplace_id = params["marketplaceId"]

    try:
        await mongo.marketplaces_collection.delete_one({
            "id": marketplace_id
        })

        return response({
            "message": "Маркетплейс клиента удален",
            "ok": True
        }, start_time=start_time)
    except Exception as e:
        return response({
            "message": str(e),
            "ok": False
        }, start_time=start_time, code=400)
