<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Species;

class SpeciesService
{
    private Species $speciesModel;

    public function __construct()
    {
        $this->speciesModel = new Species();
    }

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

    public function getById(int $id): array
    {
        $species = $this->speciesModel->findById($id);
        if (!$species) {
            throw new \RuntimeException('Especie no encontrada', 404);
        }
        return $species;
    }

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

        $id = $this->speciesModel->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->speciesModel->update($id, ['name' => $name]);
        return $this->getById($id);
    }

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