<?php

namespace App\Http\Controllers;

use App\Http\Requests\FilterFeatureStoreRequest;
use App\Http\Requests\FilterFeatureUpdateRequest;
use App\Http\Resources\FilterFeatureList;
use App\Http\Resources\FilterFeatureView;
use App\Jobs\AssignFilterFeatures;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\FilterFeature;
use Mtc\MercuryDataModels\VehicleStandardEquipment;

class FilterFeatureController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): FilterFeatureList
    {
        return new FilterFeatureList(
            FilterFeature::query()
                ->when(
                    $request->filled('search_term'),
                    fn($query) => $query->where('name', 'like', '%' . $request->input('search_term') . '%')
                )
                ->setSortBy($request->input('sort_by', 'id_desc'))
                ->setFilters($request->input('filters', []))
                ->latest()
                ->paginate()
        );
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(FilterFeatureStoreRequest $request): FilterFeatureView
    {
        /** @var FilterFeature $feature */
        $feature = FilterFeature::query()->create($request->validated());
        return new FilterFeatureView($feature);
    }

    /**
     * Display the specified resource.
     */
    public function show(FilterFeature $filterFeature): FilterFeatureView
    {
        return new FilterFeatureView($filterFeature);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(FilterFeatureUpdateRequest $request, FilterFeature $filterFeature): FilterFeatureView
    {
        $filterFeature->name = $request->input('name');
        $terms = is_array($request->input('terms'))
            ? $request->input('terms')
            : explode(',', (string) $request->input('terms'));

        $filterFeature->terms = collect($terms)
            ->map(fn($row) => trim((string) $row))
            ->filter();
        $filterFeature->save();
        $this->dispatch(new AssignFilterFeatures($filterFeature));
        return new FilterFeatureView($filterFeature);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request, FilterFeature $filterFeature): FilterFeatureList
    {
        $filterFeature->delete();
        return $this->index($request);
    }

    public function search(Request $request): LengthAwarePaginator
    {
        $query = VehicleStandardEquipment::query()
            ->distinct()
            ->select(['description']);

        $terms = explode(',', (string) $request->input('term'));
        foreach ($terms as $term) {
            $query->orWhere('description', 'like', '%' . trim($term) . '%');
        }

        return $query->paginate(100);
    }
}
