from rest_framework import serializers
from .models import Contact, Reminder


class ContactSerializer(serializers.ModelSerializer):
    """Serializer for Contact model."""
    company_name = serializers.SerializerMethodField()
    company_logo_url = serializers.SerializerMethodField()
    avatar_url = serializers.SerializerMethodField()
    created_by_name = serializers.SerializerMethodField()

    class Meta:
        model = Contact
        fields = [
            "id", "name", "email", "phone", "type", "company", "company_name",
            "company_logo_url", "position", "address", "notes", "tags",
            "avatar", "avatar_url",
            "visibility", "is_favorite",
            "created_by", "created_by_name",
            "created_at", "updated_at",
        ]
        read_only_fields = [
            "id", "company_logo_url", "avatar_url",
            "created_at", "updated_at", "created_by",
        ]

    def get_company_name(self, obj):
        if obj.company:
            return obj.company.name
        return None

    def get_company_logo_url(self, obj):
        if not obj.company or not obj.company.logo:
            return None
        request = self.context.get("request")
        url = obj.company.logo.url
        return request.build_absolute_uri(url) if request else url

    def get_avatar_url(self, obj):
        if not obj.avatar:
            return None
        request = self.context.get("request")
        url = obj.avatar.url
        return request.build_absolute_uri(url) if request else url

    def get_created_by_name(self, obj):
        if obj.created_by:
            return obj.created_by.get_full_name() or obj.created_by.username
        return None


class ReminderSerializer(serializers.ModelSerializer):
    contact_name = serializers.SerializerMethodField()

    class Meta:
        model = Reminder
        fields = [
            "id", "contact", "contact_name", "note", "remind_at", "status",
            "created_by", "created_at", "updated_at",
        ]
        read_only_fields = ["id", "created_at", "updated_at", "created_by"]

    def get_contact_name(self, obj):
        return obj.contact.name if obj.contact else None
