from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from accounts.models import Customers, CustomerDocument


def upload_document(request, customer_id):
    customer = get_object_or_404(Customers, pk=customer_id)
    if not customer.can_add_document():
        return JsonResponse({'error': 'Document limit reached. Cannot upload more than 10 documents.'}, status=400)

    if request.method == 'POST':
        document_file = request.FILES.get('document')
        if not document_file:
            return JsonResponse({'error': 'No file uploaded.'}, status=400)

        try:
            if document_file.size > 10485760:  # 10 MB limit
                return JsonResponse({'error': 'File size exceeds the limit of 10MB.'}, status=400)

            customer_document = CustomerDocument.objects.create(customer=customer, document=document_file)
            return JsonResponse({'message': 'Document uploaded successfully.'}, status=200)
        except Exception as e:
            return JsonResponse({'error': str(e), 'message': "Something went wrong"}, status=500)

    return JsonResponse({'error': 'Invalid request method.'}, status=400)
