<?php

namespace App\Controllers;

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

class CategoryController
{
    private CategoryService $service;

    public function __construct()
    {
        $this->service = new CategoryService();
    }

    /**
     * Return all categories 
     * 
     * @return void
     * 
     * @throws Exception
     */
    public function getCategories(): void
    {

        $body = json_decode(file_get_contents('php://input'), true);

        if (!$body) {
            Response::error('JSON inválido', 400);
        }

        try {
            $categories = $this->service->getAllCategories($body);

            Response::success(
                'Categories retrieved successfully',
                $categories
            );
        } catch (\InvalidArgumentException $e) {
            Response::error($e->getMessage(), 400);
        } catch (\Exception $e) {
            Response::error($e->getMessage(), 404);
        }
    }

    /**
     * Return category by id
     * 
     * @throws Exception
     * 
     * @return void
     * 
     * @param int $id
     */
    public function getById(int $id): void
    {
        try {
            $category = $this->service->getById($id);

            Response::success(
                'Category obtained successfully',
                $category
            );
        } catch (\InvalidArgumentException $e) {
            Response::error($e->getMessage(), 400);
        } catch (\Exception $e) {
            Response::error($e->getMessage(), 404);
        }
    }
}
