<?php
require_once __DIR__ . '/../controllers/SpeciesController.php';
require_once __DIR__ . '/../middleware/AuthMiddleware.php';

function handleSpeciesRoutes($path, $method, $db) {
    // Verificar autenticación para todas las rutas de especies
    if (!AuthMiddleware::authenticate()) {
        http_response_code(401);
        return json_encode([
            'success' => false,
            'message' => 'Token de autenticación requerido'
        ]);
    }

    $controller = new SpeciesController($db);
    
    // Remover 'species/' del path
    $path = preg_replace('/^species\/?/', '', $path);
    
    switch ($method) {
        case 'GET':
            if (empty($path)) {
                // GET /species
                return $controller->getAll();
            } elseif ($path === 'recommended') {
                // GET /species/recommended
                return $controller->getRecommended();
            } elseif ($path === 'search') {
                // GET /species/search?q=term
                return $controller->search();
            } elseif ($path === 'most-used') {
                // GET /species/most-used
                return $controller->getMostUsed();
            } elseif ($path === 'stats') {
                // GET /species/stats
                return $controller->getStats();
            } elseif (is_numeric($path)) {
                // GET /species/{id}
                return $controller->getById($path);
            }
            break;
            
        case 'POST':
            if (empty($path)) {
                // POST /species
                return $controller->create();
            } elseif ($path === 'initialize') {
                // POST /species/initialize
                return $controller->initializeCatalog();
            }
            break;
    }
    
    // Ruta no encontrada
    http_response_code(404);
    return json_encode([
        'success' => false,
        'message' => 'Ruta de especies no encontrada',
        'path' => $path,
        'method' => $method
    ]);
}
?>