<?php

namespace Daylight\Core\Modules\Search;

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;
use Meilisearch\Client;

class SearchServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Collection::macro('paginateMeilisearchResults', function (int $total, int $perPage, $page = null, array $options = []) {
            $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);

            $options['path'] = '/' . request()->path();

            return new LengthAwarePaginator(
                $this,
                $total,
                $perPage,
                $page,
                $options
            );
        });

        Collection::macro('flattenKeepKeys', function ($depth = 1, $dotNotation = false) {
            if ($depth) {
                $newArray = [];
                foreach ($this->items as $parentKey => $value) {
                    if (is_array($value)) {
                        $valueKeys = array_keys($value);
                        foreach ($valueKeys as $key) {
                            $subValue = $value[$key];
                            $newKey = $key;
                            if ($dotNotation) {
                                $newKey = "$parentKey.$key";
                                if ($dotNotation !== true) {
                                    $newKey = "$dotNotation.$newKey";
                                }

                                if (is_array($value[$key])) {
                                    $subValue = collect($value[$key])->flattenKeepKeys($depth - 1, $newKey)->toArray();
                                }
                            }
                            $newArray[$newKey] = $subValue;
                        }
                    } else {
                        $newArray[$parentKey] = $value;
                    }
                }

                $this->items = collect($newArray)->flattenKeepKeys(--$depth, $dotNotation)->toArray();
            }

            return collect($this->items);
        });
    }

    public function register(): void
    {
        $this->app->singleton(Client::class, function () {
            return new Client(
                url: config('scout.meilisearch.host'),
                apiKey: config('scout.meilisearch.key')
            );
        });

    }
}
