<?php

namespace App\Filter\Sorting;

use Illuminate\Database\Eloquent\Builder;
use Mtc\Filter\Contracts\IsSortOption;
use Mtc\MercuryDataModels\VehicleAttributeValue;

class VehicleAttribute implements IsSortOption
{
    /**
     * Perform sorting query adjustments
     *
     * @param Builder $query
     * @return Builder
     */
    public function handle(Builder $query, $field = ''): Builder
    {
        return $query->addSelect([
            'attribute_value' => VehicleAttributeValue::select('value_integer')
                ->whereColumn('owner_id', 'vehicles.id')
                ->where('type', 'boolean')
                ->where('slug', $field)
                ->limit(1)
        ])
            ->orderByDesc('attribute_value');
    }
}
