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("/get", tags=[""])
async def get(page: int = 0, items_per_page: int = 10):
    start_time = time()

    total = await mongo.payment_records_collection.count_documents({})
    payment_records = await mongo.payment_records_collection.find({}, {
        "_id": False
    }).limit(items_per_page).skip(items_per_page * (page - 1)).to_list(length=None)

    for payment_record in payment_records:
        payment_record["user"] = await mongo.users_collection.find_one({"id": payment_record["userId"]}, {"_id": False})
        payment_record["createdByUser"] = await mongo.users_collection.find_one({"id": payment_record["createdByUserId"]}, {"_id": False})

    return response({
        "paginationInfo": {
            "totalItems": total,
            "totalPages": round(total / items_per_page)
        },
        "paymentRecords": payment_records
    }, start_time=start_time)


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

    data = params["data"]
    work_units = data.get("workUnits", 0)

    user = await mongo.users_collection.find_one({"id": data["user"]["id"]}, {"_id": False})
    pay_rate = await mongo.pay_rates_collection.find_one(
        {"id": user.get("payRate", {}).get("id")},
        {"_id": False}
    )

    payroll_scheme = pay_rate.get("payrollScheme", {})
    total_amount = 0.0

    if payroll_scheme.get("key") == "hourly":
        overtime_threshold = pay_rate.get("overtimeThreshold", 0)
        base_hours = min(work_units, overtime_threshold)
        overtime_hours = max(work_units - overtime_threshold, 0)

        base_rate = pay_rate.get("baseRate", 0)
        overtime_rate = pay_rate.get("overtimeRate", base_rate)

        total_amount = round(base_hours * base_rate + overtime_hours * overtime_rate, 2)

    elif payroll_scheme.get("key") == "hourly":
        base_rate = pay_rate.get("baseRate", 0)
        total_amount = base_rate * work_units

    data["id"] = await mongo.get_next_id(mongo.payment_records_collection)
    data["userId"] = user["id"]
    data["createdByUserId"] = request.state.user["id"]
    data["createdAt"] = mongo.created_at()
    data["amount"] = total_amount
    data["payrollScheme"] = payroll_scheme

    await mongo.payment_records_collection.insert_one(data)
    return response({
        "message": "Начисление создано",
        "ok": True
    }, start_time=start_time)


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

    await mongo.payment_records_collection.delete_one({"id": params["paymentRecordId"]})
    return response({
        "message": "Начисление удалено",
        "ok": True
    }, start_time=start_time)
