from rest_framework import serializers
from .models import MailSender, MailEmail


class MailSenderSerializer(serializers.ModelSerializer):
    type = serializers.SerializerMethodField()

    class Meta:
        model = MailSender
        fields = ['id', 'type', 'email', 'domain', 'rule', 'note', 'created_at']

    def get_type(self, obj):
        return 'address' if obj.email else 'domain'

    def validate(self, data):
        email = data.get('email')
        domain = data.get('domain')
        if not email and not domain:
            raise serializers.ValidationError("email または domain のどちらかを指定してください")
        if email and domain:
            raise serializers.ValidationError("email と domain を同時に指定することはできません")
        return data


class MailEmailCreateSerializer(serializers.ModelSerializer):
    """Windmill からの POST 用"""
    class Meta:
        model = MailEmail
        fields = [
            'account', 'message_id', 'sender_email', 'sender_domain',
            'subject', 'body_preview', 'received_at', 'llm_verdict'
        ]


class MailEmailListSerializer(serializers.ModelSerializer):
    """フロントエンド向けメール一覧用"""
    feedback_token = serializers.SerializerMethodField()

    class Meta:
        model = MailEmail
        fields = [
            'id', 'account', 'sender_email', 'sender_domain',
            'subject', 'received_at', 'llm_verdict',
            'notified_at', 'feedback', 'feedback_at', 'feedback_token',
        ]

    def get_feedback_token(self, obj):
        if hasattr(obj, 'notification_token'):
            return str(obj.notification_token.token)
        return None


class FeedbackDetailSerializer(serializers.ModelSerializer):
    """フィードバックページ表示用"""
    class Meta:
        model = MailEmail
        fields = [
            'id', 'sender_email', 'sender_domain', 'subject',
            'body_preview', 'received_at', 'feedback'
        ]
