<?php

declare(strict_types=1);

namespace App\Handlers;

use App\Services\ProductsService;
use App\Services\SettingsService;
use Exception;
use Openguru\OpenCartFramework\Exceptions\EntityNotFoundException;
use Openguru\OpenCartFramework\Http\JsonResponse;
use Openguru\OpenCartFramework\Http\Request;
use Openguru\OpenCartFramework\Http\Response;
use Psr\Log\LoggerInterface;
use RuntimeException;

class ProductsHandler
{
    private SettingsService $settings;
    private ProductsService $productsService;
    private LoggerInterface $logger;

    public function __construct(SettingsService $settings, ProductsService $productsService, LoggerInterface $logger)
    {
        $this->settings = $settings;
        $this->productsService = $productsService;
        $this->logger = $logger;
    }

    public function index(Request $request): JsonResponse
    {
        $page = (int) $request->json('page', 1);
        $perPage = min((int) $request->json('perPage', 6), 15);
        $maxPages = (int) $request->json('maxPages', 10);
        $search = trim($request->get('search', ''));
        $filters = $request->json('filters');
        $languageId = $this->settings->config()->getApp()->getLanguageId();

        $response = $this->productsService->getProductsResponse(
            compact('page', 'perPage', 'search', 'filters', 'maxPages'),
            $languageId,
        );

        return new JsonResponse($response);
    }

    public function show(Request $request): JsonResponse
    {
        $productId = (int) $request->get('id');

        try {
            $product = $this->productsService->getProductById($productId);
        } catch (EntityNotFoundException $exception) {
            return new JsonResponse([
                'message' => 'Product with id ' . $productId . ' not found',
            ], Response::HTTP_NOT_FOUND);
        } catch (Exception $exception) {
            $this->logger->error($exception->getMessage(), ['exception' => $exception]);
            throw new RuntimeException('Error get product with id ' . $productId, 500);
        }

        return new JsonResponse([
            'data' => $product,
        ]);
    }
}
