from base64 import b64decode
from logging import getLogger

from fastapi import APIRouter, Response
from orjson import loads

from shared import exceptions as e
from shared.redis import client as cache

logger = getLogger(__name__)
router = APIRouter(
    prefix='/download',
    tags=[
        'Download',
    ],
)


@router.get('/{token}')
async def download_file(token: str):
    file_data = await cache.get(f'download:{token}')

    if file_data is None:
        raise e.NotFoundException

    data = loads(file_data)
    file_bytes = b64decode(data['data'])

    return Response(
        content=file_bytes,
        media_type=data['content_type'],
        headers={
            'Content-Disposition': f'attachment; filename="{data["filename"]}"'
        },
    )
