<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Category;

class CategoryService
{
    private Category $categoryModel;

    public function __construct()
    {
        $this->categoryModel = new Category();
    }

    public function getAll(): array
    {
        return $this->categoryModel->findAllActive();
    }

    public function getById(int $id): array
    {
        $cat = $this->categoryModel->findById($id);
        if (!$cat) {
            throw new \RuntimeException('Categoría no encontrada', 404);
        }
        return $cat;
    }

    public function create(array $data): array
    {
        $name = trim($data['name'] ?? '');
        if (empty($name)) {
            throw new \RuntimeException('El nombre es obligatorio', 422);
        }
        $id = $this->categoryModel->create(['name' => $name]);
        return $this->getById($id);
    }

    public function update(int $id, array $data): array
    {
        $this->getById($id);
        $name = trim($data['name'] ?? '');
        if (empty($name)) {
            throw new \RuntimeException('El nombre es obligatorio', 422);
        }
        $this->categoryModel->update($id, ['name' => $name]);
        return $this->getById($id);
    }

    public function delete(int $id): void
    {
        $this->getById($id);
        $this->categoryModel->delete($id);
    }
}
