<?php

namespace App\Services;

use App\Models\Category;
use Illuminate\Support\Collection;

class CategoryService
{
    public function getAllHierarchy(): Collection
    {
        return Category::with('children')->whereNull('parent_id')->get();
    }

    public function getAllFlat(): Collection
    {
        return Category::all();
    }

    public function getByLevel(int $level): Collection
    {
        return Category::atLevel($level)->get();
    }

    public function checkDuplicate(string $name, ?int $parentId, ?int $excludeId = null): bool
    {
        $query = Category::where('name', $name)->where('parent_id', $parentId);
        if ($excludeId) {
            $query->where('id', '!=', $excludeId);
        }
        return $query->exists();
    }

    public function createCategory(array $data): Category
    {
        return Category::create($data);
    }

    public function updateCategory(Category $category, array $data): bool
    {
        return $category->update($data);
    }

    public function deleteCategory(Category $category): bool
    {
        // Recursive delete is handled by database cascade if configured, 
        // but we can also handle it here if needed for specific logic.
        return $category->delete();
    }

    public function getCategoryById(int $id): ?Category
    {
        return Category::find($id);
    }
}
