<?php

namespace App\Controllers;

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

class BrandController
{
    private BrandService $service;
    public function __construct()
    {
        $this->service = new BrandService();
    }

    /**
     * Return all brands
     * 
     * @return void
     * 
     * @throws Exception
     */
    public function getBrands(): void
    {
        $body = json_decode(file_get_contents('php://input'), true);

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

        try {
            $brands = $this->service->getAllBrands($body);

            Response::success(
                'Brands retrieved successfully',
                $brands
            );
        } catch (Exception $e) {
            Response::error($e->getMessage(), 400);
        } catch (\Exception $e) {
            Response::error('SERVER_ERROR', 500);
        }
    }

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

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