from rest_framework import serializers
from drf_spectacular.utils import extend_schema_field
from drf_spectacular.types import OpenApiTypes
from typing import Optional
from sitemanagement.models import Alert

class AlertSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    object = serializers.SerializerMethodField()
    metric_value = serializers.SerializerMethodField()
    sensor_type_name = serializers.SerializerMethodField()
    
    class Meta:
        model = Alert
        fields = ('id', 'name', 'object', 'metric_value', 'sensor_type_name', 'message', 'severity', 'created_at', 'resolved')

    @extend_schema_field(OpenApiTypes.STR)
    def get_name(self, obj) -> str:
        return obj.sensor.name

    @extend_schema_field(OpenApiTypes.STR)
    def get_object(self, obj) -> Optional[str]:
        zone = obj.sensor.zones.first()
        return zone.object.title if zone else None
        
    @extend_schema_field(OpenApiTypes.STR)
    def get_metric_value(self, obj) -> str:
        if obj.metric.value is not None:
            unit = obj.sensor.signal_format.unit if obj.sensor.signal_format else ''
            return f"{obj.metric.value} {unit}".strip()
        return obj.metric.raw_value
        
    @extend_schema_field(OpenApiTypes.STR)
    def get_sensor_type_name(self, obj) -> str:
        return obj.sensor_type.name