from rest_framework import serializers
from ..models.pdf import Pdf
from ..models.customer import Customer

from rest_framework.exceptions import ValidationError
import os


class PdfSerializer(serializers.ModelSerializer):
    class Meta:
        model = Pdf
        fields = ['id', 'url', 'pdf', 'name', 'created_at']
        read_only_fields = ['id', 'created_at', 'user']
    
    def validate(self, data):
        # Safely get the request from context
        request = self.context.get('request')
        if not request:
            raise serializers.ValidationError("Request context not provided")
        
        # Check file size if image is provided
        if 'pdf' in request.FILES:
            pdf = request.FILES['pdf']
            if pdf.size > 50 * 1024 * 1024:  # 50MB limit
                raise serializers.ValidationError("Pdf file too large ( > 50MB )")
            
            # Check file extension
            ext = os.path.splitext(Pdf.name)[1].lower()
            valid_extensions = ['.pdf']
            if ext not in valid_extensions:
                raise serializers.ValidationError(f"Unsupported file extension. Supported: {', '.join(valid_extensions)}")
        
        return data