from rest_framework import serializers

from apps.analytics.models import UserEvent, UserSession


class UserEventCreateSerializer(serializers.ModelSerializer):
    """Serializer for mobile app to send events."""

    class Meta:
        model = UserEvent
        fields = [
            "event_type", "event_name", "screen_name",
            "target_type", "target_id", "target_name",
            "metadata", "session_id", "session_duration",
            "platform", "app_version", "os_version",
            "device_model", "screen_resolution", "device_id",
            "latitude", "longitude", "city", "country",
            "connection_type", "client_timestamp",
        ]


class UserEventBatchSerializer(serializers.Serializer):
    """Accepts a batch of events from the mobile app."""

    events = UserEventCreateSerializer(many=True)


class UserEventListSerializer(serializers.ModelSerializer):
    """Serializer for admin to view events."""

    username = serializers.CharField(source="user.full_name", read_only=True, default="")

    class Meta:
        model = UserEvent
        fields = [
            "id", "user", "username", "device_id",
            "event_type", "event_name", "screen_name",
            "target_type", "target_id", "target_name",
            "metadata", "session_id", "session_duration",
            "platform", "app_version", "device_model",
            "latitude", "longitude", "city", "country",
            "connection_type", "client_timestamp", "created_at",
        ]


class UserSessionCreateSerializer(serializers.ModelSerializer):
    """Serializer for mobile app to report sessions."""

    class Meta:
        model = UserSession
        fields = [
            "session_id", "device_id", "started_at", "ended_at",
            "duration_seconds", "platform", "app_version",
            "device_model", "screens_viewed", "events_count",
        ]


class UserSessionListSerializer(serializers.ModelSerializer):
    """Serializer for admin to view sessions."""

    username = serializers.CharField(source="user.full_name", read_only=True, default="")

    class Meta:
        model = UserSession
        fields = [
            "id", "user", "username", "device_id", "session_id",
            "started_at", "ended_at", "duration_seconds",
            "platform", "app_version", "device_model",
            "screens_viewed", "events_count", "created_at",
        ]


class AnalyticsSummarySerializer(serializers.Serializer):
    """Summary stats for admin dashboard."""

    total_events = serializers.IntegerField()
    total_sessions = serializers.IntegerField()
    total_users = serializers.IntegerField()
    active_users_today = serializers.IntegerField()
    active_users_week = serializers.IntegerField()
    active_users_month = serializers.IntegerField()
    avg_session_duration = serializers.FloatField()
    top_screens = serializers.ListField()
    top_events = serializers.ListField()
    events_by_day = serializers.ListField()
