from django.contrib import admin

from .models import FarmPlantAssignment, ParameterUpdateLog, PlantCatalogSnapshot, SensorData, SensorParameter


@admin.register(SensorData)
class SensorDataAdmin(admin.ModelAdmin):
    list_display = (
        "farm_uuid",
        "center_location_id",
        "weather_forecast_id",
        "sensor_keys",
        "updated_at",
    )
    list_filter = ("updated_at",)
    search_fields = ("farm_uuid", "center_location_id")

    @admin.display(description="sensor keys")
    def sensor_keys(self, obj):
        payload = obj.sensor_payload if isinstance(obj.sensor_payload, dict) else {}
        return ", ".join(payload.keys())


@admin.register(PlantCatalogSnapshot)
class PlantCatalogSnapshotAdmin(admin.ModelAdmin):
    list_display = ("backend_plant_id", "name", "is_active", "source_updated_at", "updated_at")
    search_fields = ("backend_plant_id", "name", "slug")
    list_filter = ("is_active",)


@admin.register(FarmPlantAssignment)
class FarmPlantAssignmentAdmin(admin.ModelAdmin):
    list_display = ("farm", "plant", "position", "stage", "updated_at")
    search_fields = ("farm__farm_uuid", "plant__name")
    list_filter = ("stage",)


@admin.register(SensorParameter)
class SensorParameterAdmin(admin.ModelAdmin):
    list_display = ("sensor_key", "code", "name_fa", "unit", "data_type", "created_at")
    search_fields = ("sensor_key", "code", "name_fa")
    list_filter = ("sensor_key", "data_type")


@admin.register(ParameterUpdateLog)
class ParameterUpdateLogAdmin(admin.ModelAdmin):
    list_display = ("parameter", "action", "updated_at")
    list_filter = ("action", "updated_at")
