import os
import json
import base64
import datetime
from django.core.files.base import ContentFile
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from accounts.models import Customers, CustomerDocument


@api_view(['POST'])
def upload_customer_documents(request, customer_id):
    try:
        customer = Customers.objects.get(id=customer_id)
    except Customers.DoesNotExist:
        return Response({"error": "Customer not found"}, status=status.HTTP_404_NOT_FOUND)

    documents = request.data.get("documents", [])  # List of base64/Uint8List documents
    filenames = request.data.get("filenames", [])  # Corresponding filenames

    # Validate that both lists are provided and have the same length
    if not isinstance(documents, list) or not isinstance(filenames, list):
        return Response({"error": "Invalid document format"}, status=status.HTTP_400_BAD_REQUEST)

    if len(documents) != len(filenames):
        return Response({"error": "Mismatch between documents and filenames"}, status=status.HTTP_400_BAD_REQUEST)

    saved_documents = []
    for i, document in enumerate(documents):
        original_filename = os.path.basename(filenames[i])  # Ensure safe filename
        filename, file_extension = os.path.splitext(original_filename)  # Extract extension

        # Validate file extension (allow common formats)
        allowed_extensions = [".pdf", ".jpg", ".jpeg", ".png", ".docx"]
        if file_extension.lower() not in allowed_extensions:
            return Response({"error": f"File type {file_extension} is not allowed."},
                            status=status.HTTP_400_BAD_REQUEST)

        # Prevent filename conflicts by appending timestamp
        timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        safe_filename = f"{filename}_{timestamp}{file_extension}"

        # Handle different data formats (Base64 or Uint8List)
        if isinstance(document, str):  # Base64
            try:
                format, imgstr = document.split(';base64,') if ';base64,' in document else ("", document)
                document_bytes = base64.b64decode(imgstr)
            except Exception as e:
                return Response({"error": f"Invalid base64 encoding for {original_filename}: {str(e)}"},
                                status=status.HTTP_400_BAD_REQUEST)

        elif isinstance(document, list):  # Uint8List (list of integers)
            document_bytes = bytes(document)

        else:
            return Response({"error": f"Unsupported file format for {original_filename}"},
                            status=status.HTTP_400_BAD_REQUEST)

        # Save document in the model
        doc_instance = CustomerDocument.objects.create(
            customer=customer,
            doc_name=original_filename,
            document=ContentFile(document_bytes, name=safe_filename)
        )

        saved_documents.append({
            "id": doc_instance.id,
            "doc_name": doc_instance.doc_name,
            "document_url": doc_instance.document.url
        })

    return Response({
        "message": "Documents uploaded successfully",
        "documents": saved_documents
    }, status=status.HTTP_201_CREATED)


@api_view(['GET'])
def delete_document(request, document_id,customer_id=0):
    try:
        document = CustomerDocument.objects.get(id=document_id)
        if customer_id != 0:
            if customer_id != document.customer.id:
                return Response({"error": "Unauthorized access"}, status=status.HTTP_401_UNAUTHORIZED)

        document.delete()
        return Response({"message": "Document deleted successfully"}, status=status.HTTP_200_OK)

    except CustomerDocument.DoesNotExist:
        return Response({"error": "Document not found"}, status=status.HTTP_404_NOT_FOUND)