from logging import getLogger

import xmltodict
from fastapi import APIRouter, HTTPException, Request
from orjson import dumps, loads

from apps.users.v1.schema import AEMDDemandContent
from shared.redis import client

from . import schema as s

logger = getLogger(__name__)
router = APIRouter(
    prefix='/remd',
    tags=[
        'REMD',
    ],
)


@router.post('/callback')
async def callback(request: Request):
    body_bytes = await request.body()
    if not body_bytes:
        logger.warning('Empty body')
        raise HTTPException(status_code=400, detail='Empty body')

    body = body_bytes.decode('utf-8').replace('\r', '').replace('\n', '')
    body_dict = xmltodict.parse(body)
    body = s.Remd.model_validate(body_dict)
    file_request = body.Envelope.body.sendDocumentFileRequest

    data = await client.get(f'aemd_messages:{file_request.relatesToMessage}')

    if not data:
        raise HTTPException(status_code=400, detail='Message not found')

    messageData = AEMDDemandContent(**loads(data))
    await client.delete(f'aemd_messages:{file_request.relatesToMessage}')
    await client.set(
        f'aemd:{messageData["vitaId"]}:{messageData["emdrId"]}',
        dumps(s.AEMDFileData(data=file_request.file.data)),
    )

    return
