"""
Serializers for the error monitoring API.
"""

from rest_framework import serializers

from apps.core.models import ApplicationError


class ApplicationErrorSerializer(serializers.ModelSerializer):
    """Full error details for admin dashboard."""

    user_email = serializers.SerializerMethodField()
    user_username = serializers.SerializerMethodField()
    resolved_by_username = serializers.SerializerMethodField()

    class Meta:
        model = ApplicationError
        fields = [
            "id",
            "error_id",
            "request_id",
            "error_type",
            "error_message",
            "error_stack",
            "error_code",
            "severity",
            "source",
            "endpoint",
            "http_method",
            "http_status",
            "user_agent",
            "user",
            "user_email",
            "user_username",
            "ip_address_hash",
            "metadata",
            "environment",
            "created_at",
            "resolved",
            "resolved_at",
            "resolved_by",
            "resolved_by_username",
            "resolution_notes",
        ]
        read_only_fields = fields

    def get_user_email(self, obj: ApplicationError) -> str | None:
        """Get the email of the user who encountered the error."""
        if obj.user:
            return obj.user.email
        return None

    def get_user_username(self, obj: ApplicationError) -> str | None:
        """Get the username of the user who encountered the error."""
        if obj.user:
            return obj.user.username
        return None

    def get_resolved_by_username(self, obj: ApplicationError) -> str | None:
        """Get the username of the admin who resolved the error."""
        if obj.resolved_by:
            return obj.resolved_by.username
        return None


class ApplicationErrorListSerializer(serializers.ModelSerializer):
    """Lightweight serializer for error list views."""

    class Meta:
        model = ApplicationError
        fields = [
            "id",
            "error_id",
            "error_type",
            "error_message",
            "severity",
            "source",
            "endpoint",
            "created_at",
            "resolved",
        ]
        read_only_fields = fields


class ErrorReportSerializer(serializers.Serializer):
    """Frontend error report submission."""

    error_id = serializers.UUIDField(required=False, allow_null=True)
    error_type = serializers.CharField(max_length=100)
    error_message = serializers.CharField(max_length=5000)
    error_stack = serializers.CharField(required=False, allow_blank=True, max_length=10000)
    error_code = serializers.CharField(required=False, allow_blank=True, max_length=50)
    severity = serializers.ChoiceField(
        choices=["critical", "high", "medium", "low"],
        default="medium",
    )
    endpoint = serializers.CharField(required=False, allow_blank=True, max_length=500)
    metadata = serializers.JSONField(required=False, default=dict)
    environment = serializers.JSONField(required=False, default=dict)


class ErrorStatisticsSerializer(serializers.Serializer):
    """Error statistics response for dashboard."""

    total_errors = serializers.IntegerField()
    errors_by_severity = serializers.DictField()
    errors_by_source = serializers.DictField()
    errors_by_type = serializers.ListField()
    errors_over_time = serializers.ListField()
    resolution_rate = serializers.FloatField()
    critical_count = serializers.IntegerField()
    unresolved_count = serializers.IntegerField()
    period_days = serializers.IntegerField()


class ErrorResolveSerializer(serializers.Serializer):
    """Request to resolve an error."""

    notes = serializers.CharField(required=False, allow_blank=True, max_length=1000)


class ErrorCleanupSerializer(serializers.Serializer):
    """Request to cleanup old errors."""

    days = serializers.IntegerField(min_value=1, max_value=365, default=30)
