<?php

namespace App\Http\Controllers;

use App\Http\Requests\SearchRequest;
use App\Http\Resources\SearchResponse;
use App\TaxonomyMap;
use App\Traits\ResolvesTaxonomyMapping;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class TenantTaxonomyController extends Controller
{
    use ResolvesTaxonomyMapping;

    /**
     * Search for any type records on site
     *
     * @param SearchRequest $request
     * @return SearchResponse
     */
    public function index(SearchRequest $request)
    {
        $query = TaxonomyMap::query()
            ->whereNull('taxonomy_id')
            ->whereHas('mapables', fn ($query) => $query->where('tenant', tenant('id')))
            ->when(
                $request->filled('term'),
                fn ($query) => $query->where('term', 'like', '%' . $request->input('term') . '%')
            )
            ->orderBy('term');

        $providers = $query->pluck('provider')
            ->unique()
            ->values();

        $types = $query->pluck('taxonomy_type')
            ->unique()
            ->values()
            ->map(fn ($type) => [
                'name' => __('taxonomies.' . $type),
                'slug' => $type,
            ]);

        $taxonomies = $query
            ->when(
                $request->filled('taxonomy'),
                fn ($query) => $query->where('taxonomy_type', $request->input('taxonomy', ''))
            )
            ->when($request->filled('provider'), fn ($query) => $query->where('provider', $request->input('provider')))
            ->paginate(100)
            ->through(fn (TaxonomyMap $taxonomyMap) => [
                'id' => $taxonomyMap->id,
                'name' => $taxonomyMap->term,
                'taxonomy_id' => null,
                'updated' => false,
                'type' => $taxonomyMap->taxonomy_type,
                'details' => collect($taxonomyMap->details)->reject(fn ($value, $key) => $key == 'tenant_id'),
                'metaItems' => [
                    __('taxonomies.' . $taxonomyMap->taxonomy_type),
                    $taxonomyMap->provider,
                ]
            ])->toArray();

        $taxonomies['providers'] = $providers;
        $taxonomies['types'] = $types;

        return $this->getFilters($request->input('taxonomy'), $taxonomies);
    }

    public function update(Request $request, TaxonomyMap $map): Response
    {
        $map->update([
            'taxonomy_id' => $request->input('taxonomy_id'),
        ]);

        $map->mapables()
            ->get()
            ->groupBy('tenant')
            ->each(fn ($mapables, $tenant) => $this->resolveTaxonomyMapping($mapables, $tenant, $map));

        return response([
            'status' => 'ok',
        ]);
    }
}
