from rest_framework import serializers
from django.db import models

class DataRootSerializer(serializers.ModelSerializer):
    created_by = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Make shop field optional in serializer since we might auto-assign it
        if "shop" in self.fields:
            self.fields["shop"].required = False

    def validate(self, attrs):
        # Clean up empty strings for numeric/date fields
        for field_name, value in list(attrs.items()):
            if value == "":
                model_field = self.Meta.model._meta.get_field(field_name)
                if isinstance(model_field, (models.IntegerField, models.DecimalField, models.FloatField, models.DateField, models.DateTimeField)):
                    attrs[field_name] = None

        # Automatically validate that the shop belongs to the user
        request = self.context.get("request")
        if request and request.user:
            # Set created_by to the current user
            attrs["created_by"] = request.user

            # Auto-assign shop if only one shop exists for the user and shop is not provided
            if "shop" in self.fields and not attrs.get("shop"):
                from shop_management.models.data.shop import Shop
                from account.permissions import get_user_shop_filter
                
                user_shops = Shop.objects.filter(get_user_shop_filter(request.user))
                if user_shops.count() == 1:
                    attrs["shop"] = user_shops.first()

            # Check for 'shop' field ownership
            shop = attrs.get("shop")
            if "shop" in self.fields and not shop:
                # If shop is missing but employee is present, try to get shop from employee
                employee = attrs.get("employee")
                if employee and hasattr(employee, "shop"):
                    attrs["shop"] = employee.shop
                    shop = employee.shop
                else:
                    raise serializers.ValidationError({"shop": "Shop is required."})

            if shop and hasattr(shop, 'owner'):
                from account.permissions import get_user_shop_filter
                from shop_management.models.data.shop import Shop
                
                # Check if this shop is in the user's allowed shops
                if not Shop.objects.filter(get_user_shop_filter(request.user)).filter(pk=shop.pk).exists():
                    raise serializers.ValidationError({"shop": "You do not have access to this shop."})
            
            # Check for 'employee' field ownership
            employee = attrs.get("employee")
            if employee and hasattr(employee, 'shop'):
                if not Shop.objects.filter(get_user_shop_filter(request.user)).filter(pk=employee.shop.pk).exists():
                    raise serializers.ValidationError({"employee": "This employee belongs to a shop you cannot access."})

            # Check for 'sale' field ownership
            sale = attrs.get("sale")
            if sale and hasattr(sale, 'shop'):
                if not Shop.objects.filter(get_user_shop_filter(request.user)).filter(pk=sale.shop.pk).exists():
                    raise serializers.ValidationError({"sale": "This sale belongs to a shop you cannot access."})
                        
            # Check for 'purchase' field ownership
            purchase = attrs.get("purchase")
            if purchase and hasattr(purchase, 'shop'):
                if not Shop.objects.filter(get_user_shop_filter(request.user)).filter(pk=purchase.shop.pk).exists():
                    raise serializers.ValidationError({"purchase": "This purchase belongs to a shop you cannot access."})

            # Check for 'customer' field ownership (strict user isolation)
            customer = attrs.get("customer")
            if customer and not request.user.is_superuser:
                if customer.created_by != request.user:
                    raise serializers.ValidationError({"customer": "You do not have access to this customer."})

            # Check for 'supplier' field ownership (strict user isolation)
            supplier = attrs.get("supplier")
            if supplier and not request.user.is_superuser:
                if supplier.created_by != request.user:
                    raise serializers.ValidationError({"supplier": "You do not have access to this supplier."})

        return super().validate(attrs)
