from rest_framework import serializers
from shop_management.serializers.data.base import DataRootSerializer
from shop_management.models.data.sale_return import SaleReturn, SaleReturnItem
from shop_management.serializers.data.organization import branch_profile_details

class SaleReturnItemSerializer(DataRootSerializer):
    sale_item_details = serializers.SerializerMethodField()
    batch_restorations = serializers.SerializerMethodField()

    class Meta:
        model = SaleReturnItem
        fields = '__all__'

    def get_sale_item_details(self, obj):
        if obj.sale_item:
            return {
                "id": obj.sale_item.id,
                "product": {
                    "id": obj.sale_item.product.id if obj.sale_item.product else None,
                    "name": obj.sale_item.product.name if obj.sale_item.product else None,
                },
                "sale_price": obj.sale_item.sale_price,
            }
        return None

    def get_batch_restorations(self, obj):
        return [{"batch": row.batch_id, "batch_number": row.batch.batch_number, "quantity": row.quantity, "unit_cost": row.unit_cost} for row in obj.batch_restorations.select_related("batch")]

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data["calculated_refund_amount"] = instance.calculated_refund_amount
        return data

class SaleReturnSerializer(DataRootSerializer):
    shop_details = serializers.SerializerMethodField()
    sale_details = serializers.SerializerMethodField()
    return_items = SaleReturnItemSerializer(many=True, read_only=True)

    class Meta:
        model = SaleReturn
        fields = '__all__'

    def get_shop_details(self, obj):
        if obj.shop:
            return {
                "id": obj.shop.id,
                "name": obj.shop.name,
                "profile": branch_profile_details(obj.shop),
            }
        return None

    def get_sale_details(self, obj):
        if obj.sale:
            customer_details = None
            if obj.sale.customer:
                customer_details = {
                    "id": obj.sale.customer.id,
                    "name": obj.sale.customer.name,
                }
            
            return {
                "id": obj.sale.id,
                "sale_number": obj.sale.sale_number,
                "created_at": obj.sale.created_at,
                "total_amount": obj.sale.total_amount,
                "currency_details": {
                    "id": obj.sale.currency_id,
                    "title": obj.sale.currency.title if obj.sale.currency else "",
                },
                "customer_details": customer_details,
            }
        return None
