# serializers.py

from rest_framework import serializers
from .models import Property, PropertyImage, Agent, PropertyBookmark, TempProperty, TempPropertyImage
from users.models import UserVerification

class PropertyImageSerializer(serializers.ModelSerializer):
    image_url = serializers.SerializerMethodField()
    class Meta:
        model = PropertyImage
        fields = ['id', 'image_url']

    def get_image_url(self, obj):
        request = self.context.get('request')
        if request is not None:
            return request.build_absolute_uri(obj.image.url)
        return obj.image.url

from django.utils import timezone


class PropertySerializer(serializers.ModelSerializer):
    featured_pictures = PropertyImageSerializer(many=True, read_only=True)
    thumbnail_url = serializers.SerializerMethodField()
    video_url = serializers.SerializerMethodField()
    agent_user_id = serializers.SerializerMethodField()
    agent = serializers.PrimaryKeyRelatedField(queryset=Agent.objects.all(), required=False, allow_null=True)
    posted_by_details = serializers.SerializerMethodField()
    is_bookmarked = serializers.SerializerMethodField()
    agent_details = serializers.SerializerMethodField()
    is_boosted = serializers.SerializerMethodField()
    boosted_until = serializers.SerializerMethodField()
    def get_is_boosted(self, obj):
        latest_boost = obj.boosts.order_by('-expires_at').first()
        return bool(latest_boost and latest_boost.expires_at > timezone.now())

    def get_boosted_until(self, obj):
        latest_boost = obj.boosts.order_by('-expires_at').first()
        if latest_boost and latest_boost.expires_at > timezone.now():
            return latest_boost.expires_at
        return None
    
    class Meta:
        model = Property
        fields = '__all__'
        extra_fields = ['posted_by_details', 'is_bookmarked', 'agent_details', 'agent_user_id', 'is_boosted', 'boosted_until']
        read_only_fields = ['property_id']  # property_id custom, posted_by can be set during creation
    
    def get_thumbnail_url(self, obj):
        request = self.context.get('request')
        if obj.thumbnail:
            if request is not None:
                return request.build_absolute_uri(obj.thumbnail.url)
            return obj.thumbnail.url
        return None

    def get_video_url(self, obj):
        request = self.context.get('request')
        if obj.video:
            if request is not None:
                return request.build_absolute_uri(obj.video.url)
            return obj.video.url
        return None

    def get_agent_user_id(self, obj):
        return obj.agent.user.id if obj.agent and obj.agent.user else None

    def get_posted_by_details(self, obj):
        user = obj.posted_by
        role_map = {
            '1': 'user',
            '2': 'agent',
            '3': 'organization',
        }
        user_type = role_map.get(getattr(user, 'role', '1'), 'user')

        # Check verification status  # Replace with your app name if not 'users'
        is_verified = False
        latest_verification = (
            UserVerification.objects
            .filter(user=user, status='approved')
            .order_by('-verified_at')
            .first()
        )
        if latest_verification and latest_verification.is_active():
            is_verified = True

        # Build absolute URL for profile picture
        request = self.context.get('request')
        profile_picture_url = None
        if hasattr(user, 'profile_picture') and user.profile_picture:
            if request is not None:
                profile_picture_url = request.build_absolute_uri(user.profile_picture.url)
            else:
                profile_picture_url = user.profile_picture.url

        return {
            'id': getattr(user, 'id', None),
            'full_name': getattr(user, 'full_name', ''),
            'email': getattr(user, 'email', ''),
            'phone': getattr(user, 'phone', ''),
            'type': user_type,
            'contact_details_hidden': getattr(obj, 'contact_details_hidden', False),  # property field
            'hide_address': getattr(obj, 'hide_address', False),                      # property field
            'is_verified': is_verified,
            'profile_picture': user.profile_picture.url if user.profile_picture else None,
        }



    def get_is_bookmarked(self, obj):
        request = self.context.get('request')
        user = getattr(request, 'user', None)
        if user and user.is_authenticated:
            return PropertyBookmark.objects.is_bookmarked(user, obj)
        return False

    def get_agent_details(self, obj):
        if obj.agent and obj.agent.user:
            user = obj.agent.user
            agent_latest_verification = (
                UserVerification.objects
                .filter(user=user, status='approved')
                .order_by('-verified_at')
                .first()
            )
            return {
                'id': getattr(user, 'id', None),
                'full_name': getattr(user, 'full_name', ''),
                'email': getattr(user, 'email', ''),
                'phone': getattr(user, 'phone', ''),
                'type': 'agent',
                'contact_details_hidden': getattr(obj, 'contact_details_hidden', False),
                'is_verified': bool(agent_latest_verification),
            }
        return None

    def create(self, validated_data):
        # Ensure posted_by is properly set
        posted_by = validated_data.get('posted_by')
        if not posted_by:
            # If posted_by is not provided, try to get it from the request context
            request = self.context.get('request')
            if request and hasattr(request, 'user'):
                validated_data['posted_by'] = request.user
        
        return super().create(validated_data)

class TempPropertyImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = TempPropertyImage
        fields = ['id', 'image']

class TempPropertySerializer(serializers.ModelSerializer):
    images = TempPropertyImageSerializer(many=True, read_only=True)
    class Meta:
        model = TempProperty
        fields = '__all__'  # tmp_type and property will be included automatically since fields='__all__'
