<?php

namespace App\Traits;

use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\VehicleModel;

trait ModelsForMakeInSearch
{
    protected function getModelsForMake(
        ?int $makeId,
        ?string $requiredActiveRelationship = null,
        ?string $relatedModelType = null,
        ?string $vehicleType = null
    ): Collection {
        if (!$makeId) {
            return collect();
        }

        return VehicleModel::query()
            ->where('make_id', $makeId)
            ->when($vehicleType, fn ($query) => $query->where('type', $vehicleType))
            ->when(
                $requiredActiveRelationship,
                fn ($query) => $query->whereHas(
                    $requiredActiveRelationship,
                    fn ($query) => $query->active()
                        ->when($relatedModelType, fn ($typeQuery) => $typeQuery->where('type', $relatedModelType))
                )
            )
            ->get()
            ->map(fn ($model) => [
                'code' => $model->slug ?? '',
                'label' => $model->name,
            ])
            ->prepend([
                'code' => null,
                'label' => 'All',
            ]);
    }
}
