from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from minio import Minio
from minio.error import S3Error
import json
import uuid
import urllib3

# MinIO 설정
MINIO_ENDPOINT = settings.MINIO_ENDPOINT_URL
MINIO_ACCESS_KEY = settings.MINIO_ACCESS_KEY
MINIO_SECRET_KEY = settings.MINIO_SECRET_KEY
BUCKET_NAME = settings.MINIO_DEFAULT_BUCKET

# MinIO 클라이언트 생성
client = Minio(
    MINIO_ENDPOINT,
    access_key=MINIO_ACCESS_KEY,
    secret_key=MINIO_SECRET_KEY,
    secure=True,
    http_client=urllib3.PoolManager(cert_reqs='CERT_NONE')  # SSL 검증 비활성화
)


@csrf_exempt
def upload_image(request):
    """
    이미지 업로드 및 URL 반환
    """
    if request.method == 'POST' and 'image' in request.FILES:
        image = request.FILES['image']
        unique_filename = f"uploads/{uuid.uuid4()}_{image.name}"

        try:
            # MinIO에 파일 업로드
            client.put_object(
                bucket_name=BUCKET_NAME,
                object_name=unique_filename,
                data=image,
                length=image.size,
                content_type=image.content_type,
            )

            # 전체 URL 생성
            full_url = f"https://{MINIO_ENDPOINT}/{BUCKET_NAME}/{unique_filename}"
            return JsonResponse({"url": full_url}, status=201)

        except S3Error as e:
            return JsonResponse({"error": str(e)}, status=500)

    return JsonResponse({"error": "Invalid request"}, status=400)


@csrf_exempt
def get_presigned_url(request):
    """
    Presigned URL 생성 및 반환
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            object_name = data.get('object_name')

            if not object_name:
                return JsonResponse({"error": "Missing object_name"}, status=400)

            # Presigned URL 생성
            presigned_url = client.presigned_get_object(BUCKET_NAME, object_name)
            return JsonResponse({"presigned_url": presigned_url}, status=200)
        except S3Error as e:
            return JsonResponse({"error": str(e)}, status=500)
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON"}, status=400)

    return JsonResponse({"error": "Invalid request method"}, status=405)
