import re
from time import time

from fastapi import APIRouter

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

router = APIRouter()


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

    users = await mongo.users_collection.find({
        "isDeleted": {"$ne": True}
    }, {
        "_id": False
    }).sort("id", mongo.asc).to_list()

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


@router.get("/get-managers", tags=[""])
async def get_all_managers():
    start_time = time()

    managers = await mongo.users_collection.find({
        "position.key": "sales_manager",
        "isDeleted": {"$ne": True}
    }, {
        "_id": False
    }).sort("id", mongo.asc).to_list()

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


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

    telegram_id = extract_telegram_id(data.get("comment", ""))
    if telegram_id:
        data["telegramId"] = telegram_id

    role = data.get("role")
    if not role:
        return response({
            "message": "Необходимо выбрать роль",
            "ok": False
        }, start_time=start_time)

    data["id"] = await mongo.get_next_id(mongo.users_collection)
    await mongo.users_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["data"]

    telegram_id = extract_telegram_id(data.get("comment", ""))
    if telegram_id:
        data["telegramId"] = telegram_id

    role = data.get("role")
    if not role:
        return response({
            "message": "Необходимо выбрать роль",
            "ok": False
        }, start_time=start_time)

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

    return response({
        "message": "Пользователь удален" if "isDeleted" in data else "Пользователь обновлен",
        "ok": True
    }, start_time=start_time)


@router.post("/update/department-sections/{user_id}", tags=[""])
async def update_departments_sections(user_id: int, params: dict):
    start_time = time()
    data = params["departmentSections"]

    await mongo.users_collection.update_one({
        "id": user_id
    }, {
        "$set": {
            "departmentSections": data
        }
    })

    return response({
        "message": "Отделы пользователя обновлены",
        "ok": True
    }, start_time=start_time)


def extract_telegram_id(comment: str) -> int | None:
    if not comment:
        return None

    first_line = comment.splitlines()[0]
    match = re.search(r"^[^\n:]+:\s*(\d{7,})", first_line)
    if match:
        num = int(match.group(1))
        if num > 1_000_000:
            return num
    return None
