from rest_framework import serializers

from apps.core.i18n import localized_field
from apps.promotions.models import Promotion, PromotionPlan


class PromotionPlanSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()

    class Meta:
        model = PromotionPlan
        fields = ["id", "name", "name_en", "name_ar", "type", "duration_months", "price", "is_active"]

    def get_name(self, obj):
        return localized_field(obj, "name")


class PromotionSerializer(serializers.ModelSerializer):
    plan_detail = PromotionPlanSerializer(source="plan", read_only=True)
    store_name = serializers.CharField(source="store.name_en", read_only=True)
    product_name = serializers.CharField(source="product.name_en", read_only=True, default=None)

    class Meta:
        model = Promotion
        fields = [
            "id", "owner", "store", "store_name", "product", "product_name",
            "plan", "plan_detail", "status", "start_date", "end_date",
            "amount_paid", "payment_reference", "created_at",
        ]
        read_only_fields = ["id", "owner", "status", "start_date", "end_date", "amount_paid", "payment_reference", "created_at"]


class PromotionCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Promotion
        fields = ["store", "product", "plan"]

    def validate(self, data):
        user = self.context["request"].user
        store = data["store"]

        # Verify the user owns this store
        if store.owner != user:
            raise serializers.ValidationError({"store": "You do not own this store."})

        # If product is provided, verify it belongs to the store
        product = data.get("product")
        if product and product.store != store:
            raise serializers.ValidationError({"product": "This product does not belong to the selected store."})

        # Verify plan type matches
        plan = data["plan"]
        if product and plan.type != "product":
            raise serializers.ValidationError({"plan": "Select a product promotion plan."})
        if not product and plan.type != "store":
            raise serializers.ValidationError({"plan": "Select a store promotion plan."})

        return data
