<?php

namespace App\Http\Controllers;

use App\Http\Requests\LeaseImportBulkUpdateMakeRequest;
use App\Http\Requests\LeaseImportUpdateMakeRequest;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\VehicleMake;

class LeaseImportMakeController
{
    public function index(Request $request)
    {
        $perPage = min((int) $request->input('per_page', 15), 200);

        return VehicleMake::query()
            ->when(
                $request->filled('search_term'),
                fn ($query) => $query->where('name', 'like', '%' . $request->input('search_term') . '%')
            )
            ->setSortBy($request->input('sort_by', 'name'))
            ->paginate($perPage);
    }

    public function updateBulk(LeaseImportBulkUpdateMakeRequest $request)
    {
        collect($request->input('makes') ?? [])->each(function ($make) {
            VehicleMake::query()
                ->where('id', $make['id'])
                ->update([
                    'keyloop_import_enabled' => $make['keyloop_import_enabled'],
                ]);
        });
    }

    public function show(VehicleMake $make)
    {
        return $make;
    }

    public function update(LeaseImportUpdateMakeRequest $request, VehicleMake $make)
    {
        $make->update([
            'keyloop_import_enabled' => $request->input('keyloop_import_enabled'),
        ]);
    }
}
