from datetime import datetime
from fastapi import APIRouter, Depends, Request

from api.medods import getAllEmployees
from db.schemas import Practitioner, Settings
from utils import logger, render, requestDict, p7s_save, p7s_delete


router = APIRouter()


@router.get("/", name="Staff", summary="Работа с МЧД и УКЭП")
async def settingsPage(request: Request):
    logger.info(f"📥 Получен запрос на /staff/")
    return await render(request)


@router.get("/getAll", name="getAll", summary="Получить всех работников")
async def getAll():
    logger.info(f"📥 Получен запрос на /staff/getAll")
    result = await Practitioner.getPractitioners()
    if result.success:
        practitioners = result.data
        return {"status": "ok", "data": practitioners}
    else:
        return {"status": "error", "message": result.error}


@router.get("/available", name="available", summary="Получить доступных работников")
async def available():
    logger.info(f"📥 Получен запрос на /staff/available")
    settings = await Settings.getSettings(False)
    if not settings.success:
        return {"status": "error", "message": settings.error}
    settings = settings.data
    try:
        return {
            "status": "ok",
            "data": await getAllEmployees(
                settings.medodsApiHost,
                settings.medodsApiPort,
                settings.medodsApiIdentity,
                settings.medodsApiSecretKey,
            ),
        }
    except Exception as e:
        return {
            "status": "error",
            "message": str(e),
        }


@router.post("/add", name="add", summary="Добавить работника")
async def addStaff(reqData: dict = Depends(requestDict)):
    logger.info(f"📥 Получен запрос на /staff/add")
    newPractitioner = reqData.get("body", {})
    newPractitioner["expired_at"] = datetime.strptime(
        newPractitioner.pop("expired_at"), "%Y-%m-%d"
    ).replace(hour=12, minute=0, second=0)
    if "attorney" in newPractitioner and newPractitioner["attorney"] != "":
        logger.info("🔐 МЧД получена")
    if newPractitioner["esiaAuth"]:
        logger.info("🔐 УКЭП получен")
        fileData = newPractitioner.pop("signature")
        fileInfo = p7s_save(fileData, newPractitioner["userIdLpu"])
        if fileInfo.success:
            logger.info(f"🔐 УКЭП сохранен: {fileInfo.data}")
    result = await Practitioner.addPractitioner(**newPractitioner)
    returnStatus = {"status": "ok"}
    if not result.success:
        returnStatus["status"] = "error"
        returnStatus["message"] = result.message
    if returnStatus["status"] == "ok":
        logger.info("✅ Работник добавлен")
    else:
        logger.error(returnStatus["message"])
    return returnStatus


@router.post("/update", name="update", summary="Обновить работника")
async def update(reqData: dict = Depends(requestDict)):
    logger.info(f"📥 Получен запрос на /staff/update")
    updatePractitioner = reqData.get("body", {})
    updatePractitioner["expired_at"] = datetime.strptime(
        updatePractitioner.pop("expired_at"), "%Y-%m-%d"
    ).replace(hour=12, minute=0, second=0)
    if "attorney" in updatePractitioner and updatePractitioner["attorney"] != "":
        logger.info("🔐 МЧД получена")
    if "signature" in updatePractitioner:
        logger.info("🔐 УКЭП получен")
        fileData = updatePractitioner.pop("signature")
        fileInfo = p7s_save(fileData, updatePractitioner["userIdLpu"])
        if fileInfo.success:
            logger.info(f"🔐 УКЭП сохранен: {fileInfo.data}")
    result = await Practitioner.editPractitionerByIdLpu(
        updatePractitioner.pop("userIdLpu"), **updatePractitioner
    )
    returnStatus = {"status": "ok"}
    if not result.success:
        returnStatus["status"] = "error"
        returnStatus["message"] = result.message
    if returnStatus["status"] == "ok":
        logger.info("✅ Работник обновлен")
    else:
        logger.error(returnStatus["message"])
    return returnStatus


@router.post("/delete", name="delete", summary="Удалить работника")
async def delete(reqData: dict = Depends(requestDict)):
    logger.info(f"📥 Получен запрос на /staff/delete")
    userIdLpu = reqData.get("body", {}).get("userIdLpu")
    result = await Practitioner.deletePractitionerByIdLpu(userIdLpu)
    returnStatus = {"status": "ok"}
    if not result.success:
        returnStatus["status"] = "error"
        returnStatus["message"] = result.message
    else:
        esiaAuth = result.data
        if esiaAuth:
            fileInfo = p7s_delete(userIdLpu)
            if fileInfo.success:
                logger.info(f"🔐 УКЭП удален")
            else:
                returnStatus["status"] = "error"
                returnStatus["message"] = fileInfo.message
    if returnStatus["status"] == "ok":
        logger.info("✅ Работник удален")
    else:
        logger.error(returnStatus["message"])
    return returnStatus
