<?php

namespace App\Filter\Sorting;

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

class VehicleAttributeNumeric implements IsSortOption
{
    /**
     * Perform sorting query adjustments
     *
     * @param Builder $query
     * @return Builder
     */
    public function handle(Builder $query, $field = ''): Builder
    {
        $direction = str_ends_with($field, '-asc') ? 'asc' : 'desc';
        $slug = preg_replace('/-(asc|desc)$/', '', $field);

        $type = VehicleAttribute::query()->where('slug', $slug)->value('type');
        $column = $type === 'integer' ? 'value_integer' : 'value_float';

        return $query->addSelect([
            'attribute_value' => VehicleAttributeValue::select($column)
                ->whereColumn('owner_id', 'vehicles.id')
                ->whereIn('type', ['integer', 'number'])
                ->where('slug', $slug)
                ->limit(1)
        ])->orderBy('attribute_value', $direction);
    }
}
