import structlog
from rest_framework.decorators import api_view
from rest_framework.response import Response

from vbv_lernwelt.files.serializers import PresignInputSerializer
from vbv_lernwelt.files.services import FileDirectUploadService

logger = structlog.get_logger(__name__)


@api_view(["POST"])
def presign(request):
    logger.debug(
        "presign request",
        file_type=request.data.get("file_type"),
        file_name=request.data.get("file_name"),
        label="file_upload",
    )

    if not request.user.is_authenticated:
        return Response(status=401)

    serializer = PresignInputSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)

    service = FileDirectUploadService(request.user)

    upload_file, pre_signed_data = service.start(
        file_name=serializer.validated_data["file_name"],
        file_type=serializer.validated_data["file_type"],
    )

    return Response(
        data={
            "pre_sign": pre_signed_data,
            "file_info": {
                "id": upload_file.id,
                "name": upload_file.original_file_name,
                "url": upload_file.url,
            },
        }
    )
