import uuid

from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers

from hotel.models import HotelBooking

from .models import CommissionConfig, Payment, Settlement


class PaymentSerializer(serializers.ModelSerializer):
    booking_id = serializers.IntegerField(write_only=True, required=False)
    
    class Meta:
        model = Payment
        fields = [
            'id', 'amount', 'transaction_id', 'payment_method', 
            'status', 'created_at', 'booking_id'
        ]
        read_only_fields = ['id', 'status', 'created_at', 'transaction_id']

    def create(self, validated_data):
        booking_id = validated_data.pop('booking_id', None)
        
        # Default to HotelBooking for now (extensible later)
        if booking_id:
            booking = HotelBooking.objects.get(id=booking_id)
            validated_data['content_type'] = ContentType.objects.get_for_model(HotelBooking)
            validated_data['object_id'] = booking.id
            validated_data['amount'] = booking.total_amount # Amount should match booking
        
        
        # Generate a dummy transaction ID
        validated_data['transaction_id'] = str(uuid.uuid4())
        
        return super().create(validated_data)


class InitiatePaymentSerializer(serializers.Serializer):
    booking_id = serializers.IntegerField(help_text="ID of the booking to initiate payment for")

class CommissionConfigSerializer(serializers.ModelSerializer):
    class Meta:
        model = CommissionConfig
        fields = ['id', 'hotel', 'percentage', 'created_at', 'updated_at']
        read_only_fields = ['id', 'hotel', 'created_at', 'updated_at']


class SettlementSerializer(serializers.ModelSerializer):
    booking_invoice = serializers.CharField(source='booking.invoice_number', read_only=True)
    hotel_name = serializers.CharField(source='hotel.name', read_only=True)

    class Meta:
        model = Settlement
        fields = [
            'id', 'hotel', 'hotel_name', 'booking', 'booking_invoice',
            'total_booking_amount', 'commission_amount', 'settlement_amount',
            'status', 'scheduled_for', 'processed_at', 'transaction_id',
            'created_at', 'updated_at'
        ]
        read_only_fields = fields  # Settlements should be mostly read-only via API

