from rest_framework import serializers
from apps.calls.models import TonyCall
import logging


logger = logging.getLogger(__name__)


class TonyCallListSerializer(serializers.ModelSerializer):
    company = serializers.SerializerMethodField()
    call_date_time = serializers.SerializerMethodField()

    def get_call_date_time(self, obj):
        return obj.call_date_time or obj.created_at

    class Meta:
        model = TonyCall
        fields = (
            "id",
            "call_id",
            "call_date_time",
            "called_number",
            "called_to",
            "intention",
            "status",
            "recording_url",
            "company",
            "rescheduled",
            "booking_datetime",
        )
        read_only_fields = fields

    def get_company(self, obj):
        if obj:
            try:
                return {
                    "id": obj.company.id,
                    "name": getattr(obj.company, "company_name", getattr(obj.company, "name", "")),
                    "phone": getattr(obj.company, "company_phone", getattr(obj.company, "phone", ""))
                }
            except Exception as exc:
                logger.warning(exc)
                return None
        return None


class TonyCallDetailSerializer(serializers.ModelSerializer):
    company = TonyCallListSerializer().get_company.__self__
    call_date_time = serializers.SerializerMethodField()

    def get_call_date_time(self, obj):
        return obj.call_date_time or obj.created_at

    class Meta:
        model = TonyCall
        fields = "__all__"
        read_only_fields = ("id",)
