#!/usr/bin/env python
# @Project ：django_base_ai
# @File    : frequently_used_contacts.py
# @Author  : cx
# @Time    : 11/2/2025
# @Desc    : 常用联系人管理接口
import logging

from rest_framework import serializers

from django_base_ai.system.models import FrequentlyUsedContacts
from django_base_ai.utils.json_response import DetailResponse
from django_base_ai.utils.serializers import CustomModelSerializer
from django_base_ai.utils.viewset import CustomModelViewSet

logger = logging.getLogger(__name__)


class FrequentlyUsedContactsSerializer(CustomModelSerializer):
    """
    常用联系人
    """

    avatar = serializers.SerializerMethodField(read_only=True)
    name = serializers.SerializerMethodField(read_only=True)

    def get_avatar(self, instance):
        return instance.user.avatar

    def get_name(self, instance):
        return f"{instance.user.name}({instance.user.username.upper()})"

    class Meta:
        model = FrequentlyUsedContacts
        fields = "__all__"
        read_only_fields = ["id"]


class FrequentlyUsedContactsCreateSerializer(CustomModelSerializer):
    class Meta:
        model = FrequentlyUsedContacts
        fields = "__all__"


class FrequentlyUsedContactsUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = FrequentlyUsedContacts
        fields = "__all__"


class FrequentlyUsedContactsViewSet(CustomModelViewSet):
    """
    常用联系人
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = FrequentlyUsedContacts.objects.all()
    serializer_class = FrequentlyUsedContactsSerializer
    create_serializer_class = FrequentlyUsedContactsCreateSerializer
    update_serializer_class = FrequentlyUsedContactsUpdateSerializer

    # extra_filter_backends = []

    def create(self, request, *args, **kwargs):
        uid = request.data.get("user")
        is_flag = FrequentlyUsedContacts.objects.filter(user_id=uid, creator=self.request.user.id).exists()
        if is_flag:
            return DetailResponse()
        return super().create(request, *args, **kwargs)
