<?php

namespace App\Modules\Admin\Tenancy\Repositories;

use App\Modules\Admin\Tenancy\Models\Module;
use App\Support\Lists\ListQuery;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

class ModuleRepository
{
    public function all(): Collection
    {
        return Module::query()->orderBy('name')->get();
    }

    public function paginateForIndex(Request $request): LengthAwarePaginator
    {
        $query = Module::query();

        ListQuery::applySearch($query, $request->input('q'), ['name', 'slug']);
        ListQuery::applyBoolean($query, 'is_active', $request->input('is_active'));
        ListQuery::applySort(
            $query,
            $request->input('sort'),
            $request->input('dir'),
            [
                'name' => 'name',
                'slug' => 'slug',
                'is_active' => 'is_active',
            ],
            'name',
        );

        return ListQuery::paginate($query, $request);
    }

    public function allActiveOrdered(): Collection
    {
        return Module::query()->active()->orderBy('name')->get();
    }

    /**
     * @return array<int, string>
     */
    public function activeForSelect(): array
    {
        return Module::query()
            ->active()
            ->orderBy('name')
            ->pluck('name', 'id')
            ->all();
    }

    public function create(array $data): Module
    {
        return Module::query()->create($data);
    }

    public function update(Module $module, array $data): Module
    {
        $module->update($data);

        return $module->fresh();
    }

    public function delete(Module $module): void
    {
        $module->delete();
    }
}
