from rest_framework import serializers
from django.contrib.contenttypes.models import ContentType
from .models import Notification


class NotificationSerializer(serializers.ModelSerializer):
    """Serializer for user notifications."""

    actor_type = serializers.SerializerMethodField()
    actor_display = serializers.SerializerMethodField()
    target_type = serializers.SerializerMethodField()
    target_display = serializers.SerializerMethodField()
    target_url = serializers.SerializerMethodField()

    class Meta:
        model = Notification
        fields = [
            'id',
            'verb',
            'read',
            'timestamp',
            'data',
            'actor_type',
            'actor_display',
            'target_type',
            'target_display',
            'target_url',
        ]
        read_only_fields = ['id', 'verb', 'timestamp', 'data', 'actor_type', 'actor_display', 'target_type', 'target_display', 'target_url']

    def get_actor_type(self, obj):
        """Return the type of actor (e.g., 'user', 'system')."""
        if obj.actor_content_type:
            return obj.actor_content_type.model
        return None

    def get_actor_display(self, obj):
        """Return a display name for the actor."""
        if obj.actor:
            if hasattr(obj.actor, 'full_name'):
                return obj.actor.full_name or obj.actor.email
            return str(obj.actor)
        return 'System'

    def get_target_type(self, obj):
        """Return the type of target (e.g., 'ticket', 'appointment')."""
        if obj.target_content_type:
            return obj.target_content_type.model
        return None

    def get_target_display(self, obj):
        """Return a display name for the target."""
        if obj.target:
            if hasattr(obj.target, 'subject'):
                return obj.target.subject
            if hasattr(obj.target, 'title'):
                return obj.target.title
            if hasattr(obj.target, 'name'):
                return obj.target.name
            return str(obj.target)
        return None

    def get_target_url(self, obj):
        """Return a frontend URL for the target object."""
        if not obj.target_content_type:
            return None

        model = obj.target_content_type.model
        target_id = obj.target_object_id

        # Map model types to frontend URLs
        url_map = {
            'ticket': f'/tickets?id={target_id}',
            'event': f'/scheduler?event={target_id}',
            'appointment': f'/scheduler?appointment={target_id}',
        }

        return url_map.get(model)
