<?php

namespace App\Controllers;

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

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

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

        if (!$body) {
            Response::error('INVALID_JSON', 400);
        }

        try {
            $products = $this->service->getAllProducts($body);

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

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

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