from rest_framework import serializers
from .models import State, Locality, Area, Location


class StateSerializer(serializers.ModelSerializer):
    class Meta:
        model = State
        fields = ['id', 'name', 'code', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']

        def validate(self, data):
            # Check for duplicate name
            if State.objects.filter(name=data['name']).exists():
                raise serializers.ValidationError({"name": "ولاية بهذا الاسم موجودة بالفعل."})
            # Check for duplicate code
            if State.objects.filter(code=data['code']).exists():
                raise serializers.ValidationError({"code": "هذا الكود موجود بالفعل."})
            return data


class LocalitySerializer(serializers.ModelSerializer):
    state_name = serializers.CharField(source='state.name', read_only=True)

    class Meta:
        model = Locality
        fields = ['id', 'name', 'code', 'state', 'state_name', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']


class AreaSerializer(serializers.ModelSerializer):
    locality_name = serializers.CharField(source='locality.name', read_only=True)
    state_name = serializers.CharField(source='locality.state.name', read_only=True)

    class Meta:
        model = Area
        fields = ['id', 'name', 'code', 'locality', 'locality_name', 'state_name', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']

class LocationSerializer(serializers.ModelSerializer):
    area_name = serializers.CharField(source='area.name', read_only=True)
    locality_name = serializers.CharField(source='area.locality.name', read_only=True)
    state_name = serializers.CharField(source='area.locality.state.name', read_only=True)

    class Meta:
        model = Location
        fields = [
            'id', 'name', 'code', 'area', 'area_name', 'locality_name', 'state_name',
            'zoning', 'latitude', 'longitude', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']