from rest_framework import serializers
from .models import BackToBase
from bookings.models import Booking
from bookings.serializers import BookingSerializer
from riders.serializers import RiderSerializer
from users.serializers import UserSerializer

class BackToBaseSerializer(serializers.ModelSerializer):
    booking = serializers.SlugRelatedField(slug_field='booking_id', queryset=Booking.objects.all())
    booking_details = BookingSerializer(source='booking', read_only=True)
    rider_details = RiderSerializer(source='rider', read_only=True)
    customer_details = UserSerializer(source='customer', read_only=True)

    class Meta:
        model = BackToBase
        fields = [
            'id', 'booking', 'booking_details', 
            'rider', 'rider_details', 
            'customer', 'customer_details', 
            'poc_name', 'poc_mobile', 'reason',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['rider', 'customer', 'created_at', 'updated_at']

    def create(self, validated_data):
        # Auto-populate rider and customer from the booking
        booking = validated_data.get('booking')
        request = self.context.get('request')
        user = request.user if request else None

        if booking:
            # If the user creating this is a rider, set them as the rider for this entry
            if user and hasattr(user, 'rider_profile'):
                validated_data['rider'] = user.rider_profile
            else:
                validated_data['rider'] = booking.rider

            validated_data['customer'] = booking.user
        return super().create(validated_data)
