<?php

declare(strict_types=1);

namespace App\Handlers;

use App\Services\TelegramCustomerService;
use Openguru\OpenCartFramework\Http\JsonResponse;
use Openguru\OpenCartFramework\Http\Request;
use Openguru\OpenCartFramework\Http\Response;
use Openguru\OpenCartFramework\Support\Arr;
use Openguru\OpenCartFramework\TeleCartPulse\TrackingIdGenerator;
use Openguru\OpenCartFramework\Telegram\Enums\TelegramHeader;
use Openguru\OpenCartFramework\Telegram\Exceptions\DecodeTelegramInitDataException;
use Openguru\OpenCartFramework\Telegram\TelegramInitDataDecoder;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Throwable;

class TelegramCustomerHandler
{
    private TelegramCustomerService $telegramCustomerService;
    private LoggerInterface $logger;
    private TelegramInitDataDecoder $initDataDecoder;

    public function __construct(
        TelegramCustomerService $telegramCustomerService,
        LoggerInterface $logger,
        TelegramInitDataDecoder $initDataDecoder
    ) {
        $this->telegramCustomerService = $telegramCustomerService;
        $this->logger = $logger;
        $this->initDataDecoder = $initDataDecoder;
    }

    /**
     * Сохранить или обновить Telegram-пользователя
     *
     * @param Request $request HTTP запрос с данными пользователя
     * @return JsonResponse JSON ответ с результатом операции
     */
    public function saveOrUpdate(Request $request): JsonResponse
    {
        try {
            $customer = $this->telegramCustomerService->saveOrUpdate(
                $this->extractTelegramUserData($request)
            );

            return new JsonResponse([
                'data' => [
                    'tracking_id' => Arr::get($customer, 'tracking_id'),
                ],
            ], Response::HTTP_OK);
        } catch (Throwable $e) {
            $this->logger->error('Could not save telegram customer data', ['exception' => $e]);

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

    /**
     * Извлечь данные Telegram пользователя из запроса
     *
     * @param Request $request HTTP запрос
     * @return array Данные пользователя
     * @throws RuntimeException|DecodeTelegramInitDataException невозможно извлечь данные пользователя из Request
     */
    private function extractTelegramUserData(Request $request): array
    {
        $telegramUserData = $request->json('user');

        if (! $telegramUserData) {
            $telegramUserData = $this->extractUserDataFromInitData($request);
        }

        return $telegramUserData;
    }

    /**
     * @throws DecodeTelegramInitDataException
     */
    private function extractUserDataFromInitData(Request $request): array
    {
        $raw = $request->header(TelegramHeader::INIT_DATA);
        if (! $raw) {
            throw new RuntimeException('No init data found in http request header');
        }

        $initData = $this->initDataDecoder->decode($raw);

        return Arr::get($initData, 'user');
    }
}
