from django.conf import settings
from rest_framework import serializers

from .models import AccessLog, Hit, Site


class AccessLogSerializer(serializers.ModelSerializer):
    class Meta:
        model = AccessLog
        fields = [
            "id", "resource_type", "resource_id", "resource_slug",
            "path", "method", "status_code", "response_time_ms",
            "country", "country_code", "device", "os", "browser",
            "referer_host", "tags", "utm_source", "utm_medium", "utm_campaign",
            "created_at",
        ]
        read_only_fields = fields


class SiteSerializer(serializers.ModelSerializer):
    snippet = serializers.SerializerMethodField()
    tag_src = serializers.SerializerMethodField()

    class Meta:
        model = Site
        fields = [
            "id", "name", "domain", "public_key", "is_active",
            "favicon_url", "title", "description",
            "snippet", "tag_src", "created_at", "updated_at",
        ]
        read_only_fields = [
            "id", "public_key", "favicon_url", "title", "description",
            "snippet", "tag_src", "created_at", "updated_at",
        ]

    def _base_url(self) -> str:
        return getattr(settings, "ANALYTICS_PUBLIC_BASE_URL", "").rstrip("/")

    def get_tag_src(self, obj) -> str:
        return f"{self._base_url()}/api/analytics/tag.js"

    def get_snippet(self, obj) -> str:
        src = self.get_tag_src(obj)
        return (
            f'<script async defer src="{src}" '
            f'data-site="{obj.public_key}"></script>'
        )


class HitSerializer(serializers.ModelSerializer):
    class Meta:
        model = Hit
        fields = [
            "id", "site", "event_type", "event_name", "path", "hostname", "title",
            "country", "country_code", "device", "os", "browser",
            "referer_host", "utm_source", "utm_medium", "utm_campaign",
            "props", "created_at",
        ]
        read_only_fields = fields
