from rest_framework import serializers

from apps.api.v1.serializers.rides import RideListOutputSerializer
from apps.rides.models import Ride
from apps.rides.models.credits import RideCredit


class RideCreditSerializer(serializers.ModelSerializer):
    """Serializer for user ride credits."""

    ride_id = serializers.PrimaryKeyRelatedField(queryset=Ride.objects.all(), source="ride", write_only=True)
    ride = RideListOutputSerializer(read_only=True)

    class Meta:
        model = RideCredit
        fields = [
            "id",
            "ride",
            "ride_id",
            "count",
            "rating",
            "first_ridden_at",
            "last_ridden_at",
            "notes",
            "display_order",
            "created_at",
            "updated_at",
        ]
        read_only_fields = ["id", "created_at", "updated_at"]

    def validate(self, attrs):
        """
        Validate data.
        """
        # Ensure dates make sense
        first = attrs.get("first_ridden_at")
        last = attrs.get("last_ridden_at")
        if first and last and last < first:
            raise serializers.ValidationError("Last ridden date cannot be before first ridden date.")

        return attrs

    def create(self, validated_data):
        """Create a new ride credit."""
        user = self.context["request"].user
        validated_data["user"] = user
        return super().create(validated_data)
