from time import time

from fastapi import APIRouter

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

router = APIRouter()


@router.get("/get-by-id", tags=[""])
async def get_by_id(product_id: int = None):
    start_time = time()

    product = await mongo.products_collection.find_one({
        "id": product_id
    }, {
        "_id": False
    })

    return response(product, start_time=start_time)


@router.get("/get", tags=[""])
async def get(client_id: int = None, search_input: str = None, page: int = 0, items_per_page: int = 10):
    start_time = time()
    filter = dict()

    if client_id:
        filter["clientId"] = client_id

    if search_input:
        filter["$or"] = [
            {
                "name": {
                    "$regex": search_input
                }
            },
            {
                "article": {
                    "$regex": search_input
                }
            },
            {
                "factoryArticle": {
                    "$regex": search_input
                }
            },
            {
                "barcodes": {
                    "$regex": search_input
                }
            }
        ]

    products = await mongo.products_collection.find(filter, {
        "_id": False
    }).limit(items_per_page).skip(items_per_page * page).to_list()
    products_count = await mongo.products_collection.count_documents(filter)

    return response({
        "paginationInfo": {
            "totalItems": products_count,
            "totalPages": round(products_count / items_per_page)
        },
        "products": products
    }, start_time=start_time)


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

    try:
        await mongo.products_collection.insert_one(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("/update", tags=[""])
async def update(params: dict):
    start_time = time()
    data = params["product"]

    try:
        await mongo.products_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()
    product_id = params["productId"]

    try:
        await mongo.products_collection.delete_one({
            "id": product_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)
