import re
from fastapi import APIRouter, Depends, Request
from api.n3health import checkConnection as n3healthCheckConnection
from api.medods import checkConnection as medodsCheckConnection, generate_token
from db.schemas import Settings
from utils import logger, render, requestDict


router = APIRouter()


@router.get("/", name="Settings", summary="Настройки")
async def settingsPage(request: Request):
    return await render(request)


@router.get("/get", name="getSettings", summary="Получить настройки")
async def getSettings():
    settings = await Settings.getSettings()
    return settings.data


@router.post("/update-password", name="updatePassword", summary="Обновить пароль")
async def updatePassword(reqData: dict = Depends(requestDict)):
    logger.info(f"📥 Получен запрос на /update-password")
    response = {"status": "error"}
    currentPassword = reqData.get("body", {}).get("currentPassword", "")
    checkPassword = await Settings.verifyPassword(currentPassword)
    if checkPassword.success:
        newPassword = reqData.get("body", {}).get("newPassword", "")
        await Settings.updateSettings(password=newPassword)
        response["status"] = "ok"
    return response


@router.post("/test-medods", name="testMedods", summary="Проверить соединение с Медодс")
async def testMedods(reqData: dict = Depends(requestDict)):
    logger.info(f"📥 Получен запрос на /test-medods")
    medodsApi = reqData.get("body", {})
    responseSatus = {"status": "error"}
    try:
        apiToken = generate_token(
            medodsApi.get("identity", ""), medodsApi.get("secretKey", "")
        )
    except Exception as e:
        logger.error(f"Ошибка генерации токена: {str(e)}", exc_info=True)
        responseSatus["message"] = "Ошибка генерации токена. Проверьте файл с ключами."
        return responseSatus

    host = medodsApi.get("host", None)
    if host:
        host = re.sub(r"^https?://", "", host)
    connection = await medodsCheckConnection(host, medodsApi.get("port", 0), apiToken)
    if not connection.success:
        responseSatus["message"] = "Ошибка соединения с Медодс. Проверьте параметры."
        return responseSatus
    responseSatus = {"status": "ok"}
    logger.info("✅ Соединение с Медодс установлено")
    return responseSatus


@router.post(
    "/save-medods", name="saveMedods", summary="Сохранить параметры соединения с Медодс"
)
async def saveMedods(reqData: dict = Depends(requestDict)):
    logger.info(f"📥 Получен запрос на /save-medods")
    medodsApi = reqData.get("body", {})
    host = medodsApi.get("host", None)
    if host:
        host = re.sub(r"^https?://", "", host)
    medodsData = {
        "medodsApiHost": host,
        "medodsApiPort": medodsApi.get("port", None),
        "medodsApiIdentity": medodsApi.get("identity", None),
        "medodsApiSecretKey": medodsApi.get("secretKey", None),
    }
    responseStatus = {"status": "ok"}
    for value in medodsData.values():
        if value is None:
            responseStatus["status"] = "error"
            responseStatus["message"] = "Некоторые поля не заполнены"
            logger.error("Некоторые поля не заполнены")
            return responseStatus
    update = await Settings.updateSettings(**medodsData)
    if not update.success:
        responseStatus["status"] = "error"
        responseStatus["message"] = update.message
        logger.error(update.message)
    else:
        logger.info("✅ Параметры соединения с Медодс сохранены")
    return responseStatus


@router.post(
    "/test-n3health", name="testN3health", summary="Проверить соединение с N3Health"
)
async def testN3health(reqData: dict = Depends(requestDict)):
    logger.info(f"📥 Получен запрос на /test-n3health")
    n3healthApi = reqData.get("body", {})
    responseSatus = {"status": "error"}

    connection = await n3healthCheckConnection(**n3healthApi)

    if not connection.success:
        responseSatus["message"] = "Ошибка соединения с N3Health. Проверьте параметры."
        return responseSatus
    responseSatus = {"status": "ok"}
    logger.info("✅ Соединение с N3Health установлено")
    return responseSatus


@router.post(
    "/save-n3health",
    name="saveN3health",
    summary="Сохранить параметры соединения с N3Health",
)
async def saveN3health(reqData: dict = Depends(requestDict)):
    logger.info(f"📥 Получен запрос на /save-n3health")
    n3healthApi = reqData.get("body", {})
    n3healthData = {
        "n3healthHost": n3healthApi.get("host", None),
        "n3healthAutorization": n3healthApi.get("authorization", None),
        "n3healthXIdLpu": n3healthApi.get("xIdLpu", None),
    }
    responseStatus = {"status": "ok"}
    for value in n3healthData.values():
        if value is None:
            responseStatus["status"] = "error"
            responseStatus["message"] = "Некоторые поля не заполнены"
            logger.error("Некоторые поля не заполнены")
            return responseStatus
    update = await Settings.updateSettings(**n3healthData)
    if not update.success:
        responseStatus["status"] = "error"
        responseStatus["message"] = update.message


@router.post(
    "/update-expiration-alert",
    name="updateExpirationAlert",
    summary="Обновить настройку expirationAlert",
)
async def updateExpirationAlert(reqData: dict = Depends(requestDict)):
    logger.info(f"📥 Получен запрос на /update-expiration-alert")
    responseStatus = {"status": "error"}
    try:
        expirationAlert = reqData.get("body", {}).get("expirationAlert", "")
        await Settings.updateSettings(expirationAlert=expirationAlert)
        responseStatus["status"] = "ok"
        logger.info("✅ Настройка expirationAlert обновлена")
    except Exception as e:
        logger.error(
            f"Ошибка обновления настройки expirationAlert: {str(e)}", exc_info=True
        )
    return responseStatus
