<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;
use App\Services\CategoryService;

class CategoryController extends BaseController
{
    private CategoryService $categoryService;

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

    public function index(): void
    {
        $cats = $this->categoryService->getAll();
        Response::success($cats, 'Categorías consultadas correctamente');
    }

    public function show(): void
    {
        $id = (int) $this->getRouteParam('id');
        try {
            $cat = $this->categoryService->getById($id);
            Response::success($cat, 'Categoría consultada correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function store(): void
    {
        $data = $this->request->body();
        try {
            $cat = $this->categoryService->create($data);
            Response::created($cat, 'Categoría 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 {
            $cat = $this->categoryService->update($id, $data);
            Response::success($cat, 'Categoría actualizada correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function destroy(): void
    {
        $id = (int) $this->getRouteParam('id');
        try {
            $this->categoryService->delete($id);
            Response::success(null, 'Categoría eliminada correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }
}
