<?php

namespace App\Services;

use App\Repositories\Eloquent\CategoryRepository;
use Illuminate\Support\Str;

class CategoryService
{
    public function __construct(
        protected CategoryRepository $categoryRepository,
        protected LoggingService $loggingService
    ) {}

    public function getAll()
    {
        $this->loggingService->logInfo('Fetching all categories');
        return $this->categoryRepository->all();
    }

    public function getActive()
    {
        $this->loggingService->logInfo('Fetching active categories');
        return $this->categoryRepository->getActive();
    }

    public function getWithProducts()
    {
        $this->loggingService->logInfo('Fetching categories with products');
        return $this->categoryRepository->getWithProducts();
    }

    public function find(int $id)
    {
        $this->loggingService->logInfo('Finding category', ['id' => $id]);
        return $this->categoryRepository->find($id);
    }

    public function findBySlug(string $slug)
    {
        $this->loggingService->logInfo('Finding category by slug', ['slug' => $slug]);
        return $this->categoryRepository->findBySlug($slug);
    }

    public function create(array $data)
    {
        $this->loggingService->logInfo('Creating category', ['data' => $data]);

        $data['slug'] = $data['slug'] ?? Str::slug($data['name']);

        return $this->categoryRepository->create($data);
    }

    public function update(int $id, array $data)
    {
        $this->loggingService->logInfo('Updating category', ['id' => $id, 'data' => $data]);

        if (isset($data['name']) && !isset($data['slug'])) {
            $data['slug'] = Str::slug($data['name']);
        }

        return $this->categoryRepository->update($id, $data);
    }

    public function delete(int $id)
    {
        $this->loggingService->logInfo('Deleting category', ['id' => $id]);
        return $this->categoryRepository->delete($id);
    }

    public function restore(int $id)
    {
        $this->loggingService->logInfo('Restoring category', ['id' => $id]);
        $category = $this->categoryRepository->findTrashed($id);
        if ($category && $category->trashed()) {
            return $category->restore();
        }
        return false;
    }
}
