from __future__ import annotations

import os
import uuid
from django.http import HttpRequest, JsonResponse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_protect
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from .conf import get_setting


@csrf_protect
@require_POST
def image_upload(request: HttpRequest) -> JsonResponse:
    if "image" not in request.FILES:
        return JsonResponse({"error": "No image provided."}, status=400)

    image = request.FILES["image"]
    allowed: list[str] = get_setting("allowed_image_types")
    max_mb: int = get_setting("max_image_size_mb")

    if image.content_type not in allowed:
        return JsonResponse({"error": "File type not allowed."}, status=400)

    if image.size > max_mb * 1024 * 1024:
        return JsonResponse(
            {"error": f"File exceeds {max_mb}MB limit."}, status=400
        )

    ext: str = os.path.splitext(image.name)[1].lower()
    filename: str = f"{uuid.uuid4().hex}{ext}"
    upload_path: str = get_setting("upload_path")
    saved_path: str = default_storage.save(
        os.path.join(upload_path, filename), ContentFile(image.read())
    )
    url: str = default_storage.url(saved_path)
    return JsonResponse({"url": url})
