<?php

namespace App\Http\Controllers;

use App\VehicleType;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Mtc\MercuryDataModels\VehicleModel;

class ModelController extends Controller
{
    /**
     * Display a listing of body vehicle model
     *
     * @param Request $request
     * @param int $make_id
     * @return Response
     */
    public function index(Request $request, $make_id): Response
    {
        return response([
            'data' => VehicleModel::query()
                ->with('filterIndex')
                ->ofMake($make_id)
                ->when($request->input('type'), function ($query, $type) {
                    if (in_array($type, [VehicleType::CAMPERVAN->value, VehicleType::MOTORHOME->value])) {
                        // AutoTrader's taxonomy has no campervan type
                        // campervans are a body type subtype of motorhome (see VehicleImportFlow)
                        // so campervan and motorhome lookups share the same model pool
                        $query->where(fn ($q) => $q
                            ->ofType(VehicleType::CAMPERVAN->value)
                            ->orWhere(fn ($oq) => $oq->ofType(VehicleType::MOTORHOME->value)));
                    } else {
                        $query->ofType($type);
                    }
                })
                ->orderBy('name')
                ->get()
        ]);
    }

    /**
     * Display the specified vehicle model.
     *
     * @param  VehicleModel $model
     * @return VehicleModel
     */
    public function show(VehicleModel $model)
    {
        return $model;
    }
}
