<?php

namespace App\Repositories\Eloquent;

use App\Enums\MenuLocation;
use App\Models\Menu;
use App\Repositories\Contracts\MenuRepositoryInterface;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Cache;

/**
 * @extends BaseRepository<Menu>
 */
class MenuRepository extends BaseRepository implements MenuRepositoryInterface
{
    public function __construct(Menu $model)
    {
        parent::__construct($model);
    }

    /**
     * @param  array<string, mixed>  $filters
     * @return LengthAwarePaginator<int, Menu>
     */
    public function paginate(array $filters = [], int $perPage = 15): LengthAwarePaginator
    {
        $query = $this->model->newQuery();

        if (! empty($filters['location'])) {
            $query->where('location', $filters['location']);
        }

        return $query->whereNull('parent_id')
            ->with('children')
            ->orderBy('order_index')
            ->paginate($perPage);
    }

    /**
     * @return Collection<int, Menu>
     */
    public function getByLocation(MenuLocation $location): Collection
    {
        return Cache::remember("menus.{$location->value}", 3600, fn () => $this->model->newQuery()
            ->where('location', $location)
            ->where('is_active', true)
            ->whereNull('parent_id')
            ->with(['children' => fn ($q) => $q->where('is_active', true)->orderBy('order_index')])
            ->orderBy('order_index')
            ->get());
    }

    /**
     * @param  array<int, array{id: int, order_index: int, parent_id?: int|null}>  $items
     */
    public function reorder(array $items): void
    {
        foreach ($items as $item) {
            $this->model->newQuery()
                ->where('id', $item['id'])
                ->update([
                    'order_index' => $item['order_index'],
                    'parent_id' => $item['parent_id'] ?? null,
                ]);
        }
    }
}
