<?php

namespace App\Services\Master;

use App\Models\Category;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;

class CategoryService
{
    public function paginateForIndex(array $tableQuery): LengthAwarePaginator
    {
        $query = Category::query()
            ->when($tableQuery['search'] !== '', function (Builder $query) use ($tableQuery): void {
                $search = $tableQuery['search'];
                $query->where(function (Builder $query) use ($search): void {
                    $query->where('name', 'like', "%{$search}%");
                });
            });

        $this->applySorting($query, $tableQuery['sort'], $tableQuery['direction']);

        return $query
            ->paginate(25)
            ->withQueryString();
    }

    public function create(array $validated): void
    {
        Category::create($validated);
    }

    public function update(Category $category, array $validated): void
    {
        $category->update($validated);
    }

    public function delete(Category $category): void
    {
        $category->delete();
    }

    public function getSelectOptions(): array
    {
        return Category::query()
            ->orderBy('name')
            ->get(['id', 'name'])
            ->map(fn (Category $category) => [
                'value' => $category->id,
                'label' => $category->name,
            ])
            ->all();
    }

    private function applySorting(Builder $query, string $sort, string $direction): void
    {
        if (in_array($sort, ['name', 'slug'], true)) {
            $query->orderBy($sort, $direction);

            return;
        }

        $query->latest();
    }
}
