<?php

declare(strict_types=1);

namespace App\Handlers;

use Openguru\OpenCartFramework\Http\Request;
use Openguru\OpenCartFramework\TeleCartPulse\PulseIngestException;
use Openguru\OpenCartFramework\TeleCartPulse\TeleCartPulseService;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

class TelemetryHandler
{
    private TeleCartPulseService $teleCartPulseService;
    private LoggerInterface $logger;

    public function __construct(
        TeleCartPulseService $teleCartPulseService,
        LoggerInterface $logger
    ) {
        $this->teleCartPulseService = $teleCartPulseService;
        $this->logger = $logger;
    }

    /**
     * @throws PulseIngestException
     */
    public function ingest(Request $request): JsonResponse
    {
        $this->teleCartPulseService->handleIngest($request->json());

        return new JsonResponse([], Response::HTTP_NO_CONTENT);
    }

    public function heartbeat(): JsonResponse
    {
        try {
            $this->teleCartPulseService->handleHeartbeat();
        } catch (Throwable $e) {
            $this->logger->warning('TeleCart Pulse Heartbeat failed: ' . $e->getMessage(), ['exception' => $e]);
        }

        return new JsonResponse(['status' => 'ok']);
    }
}
