from json import dumps
from logging import getLogger

from fastapi import APIRouter
from sqlmodel import select

from apps.users.models import User
from clients import clients as c
from database import AsyncSessionDep
from shared.exceptions import UnknownException
from shared.redis import client as cache

from . import schema as s

logger = getLogger(__name__)
router = APIRouter(
    prefix='/tmk',
    tags=[
        'TMK',
    ],
)


@router.post('/update')
async def update(session: AsyncSessionDep, update: s.TMKUpdate):
    guid = update.tmk_guid
    info = await c.tmk_api.getInfo(guid)
    snils = info.patient_snils

    try:
        patient = await c.vitacore_api.findBySnils(snils)
    except UnknownException:
        return

    user_stmt = select(User).where(User.vita_id == patient.patId).limit(1)
    user = await session.scalar(user_stmt)

    if user is None:
        return

    key = f'tmk:{user.id}:{guid}'
    value = {'id': info.id, 'status': info.tmk_status_name, 'is_read': False}
    await cache.set(key, dumps(value))
