<?php

namespace App\Services\Master;

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

class CategoryService
{
    use CachesQuery;

    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);
        $this->cacheForget('master:categories:options');
        $this->cacheForget('homepage:page_data');
    }

    public function update(Category $category, array $validated): void
    {
        $category->update($validated);
        $this->cacheForget('master:categories:options');
        $this->cacheForget('homepage:page_data');
    }

    public function delete(Category $category): void
    {
        $category->delete();
        $this->cacheForget('master:categories:options');
        $this->cacheForget('homepage:page_data');
    }

    public function getSelectOptions(): array
    {
        return $this->cacheRemember('master:categories:options', 3600, function () {
            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();
    }
}
