from rest_framework import serializers
from .models import Announcement


class AnnouncementSerializer(serializers.ModelSerializer):
    category_label     = serializers.CharField(source="get_category_display",     read_only=True)
    neighborhood_label = serializers.CharField(source="get_neighborhood_display", read_only=True)
    priority_label     = serializers.CharField(source="get_priority_display",     read_only=True)
    created_by_name    = serializers.SerializerMethodField()
    created_by_id      = serializers.SerializerMethodField()
    views_count        = serializers.SerializerMethodField()
    image_url          = serializers.SerializerMethodField()
    is_expired         = serializers.SerializerMethodField()

    class Meta:
        model  = Announcement
        fields = [
            "id", "title", "body",
            "category", "category_label",
            "neighborhood", "neighborhood_label",
            "priority", "priority_label",
            "image", "image_url", "link",
            "is_active", "is_broadcast",
            "created_by_name", "created_by_id",
            "views_count", "is_expired",
            "created_at", "updated_at", "expires_at",
        ]

    def get_created_by_name(self, obj):
        return obj.created_by.username if obj.created_by else "ThikaConnect Admin"

    def get_created_by_id(self, obj):
        return obj.created_by_id

    def get_views_count(self, obj):
        return obj.views.count()

    def get_image_url(self, obj):
        if not obj.image:
            return None
        request = self.context.get("request")
        if request:
            return request.build_absolute_uri(obj.image.url)
        return f"http://127.0.0.1:8000{obj.image.url}"

    def get_is_expired(self, obj):
        if not obj.expires_at:
            return False
        from django.utils import timezone
        return timezone.now() > obj.expires_at
