<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;
use App\Services\SpeciesService;

class SpeciesController extends BaseController
{
    private SpeciesService $speciesService;

    public function __construct($request)
    {
        parent::__construct($request);
        $this->speciesService = new SpeciesService();
    }

    public function index(): void
    {
        $species = $this->speciesService->getAll();
        Response::success($species, 'Especies consultadas correctamente');
    }

    public function show(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $species = $this->speciesService->getById($id);
            Response::success($species, 'Especie consultada correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function store(): void
    {
        $data = $this->request->body();

        try {
            $species = $this->speciesService->create($data);
            Response::created($species, 'Especie creada correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function update(): void
    {
        $id = (int) $this->getRouteParam('id');
        $data = $this->request->body();

        try {
            $species = $this->speciesService->update($id, $data);
            Response::success($species, 'Especie actualizada correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function destroy(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $this->speciesService->delete($id);
            Response::success(null, 'Especie eliminada correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }
}
