<?php

namespace Openguru\OpenCartFramework\Telegram;

use JsonException;
use Openguru\OpenCartFramework\Telegram\Exceptions\DecodeTelegramInitDataException;

class TelegramInitDataDecoder
{
    /**
     * @throws DecodeTelegramInitDataException
     */
    public function decode(string $initDataDecoded): array
    {
        $initDataString = base64_decode($initDataDecoded);

        if ($initDataString === false) {
            throw new DecodeTelegramInitDataException('Could not decode init data.');
        }

        try {
            return $this->parseInitDataStringToArray($initDataString);
        } catch (JsonException $e) {
            throw new DecodeTelegramInitDataException(
                'Error decoding Telegram init data JSON: ' . $e->getMessage(),
                500,
                $e
            );
        }
    }

    /**
     * @throws JsonException
     */
    public function parseInitDataStringToArray(string $initData): array
    {
        parse_str($initData, $parsed);

        foreach ($parsed as $key => $value) {
            if ($this->isValidJson($value)) {
                $parsed[$key] = json_decode(urldecode($value), true, 512, JSON_THROW_ON_ERROR);
            } else {
                $parsed[$key] = $value;
            }
        }

        return $parsed;
    }

    private function isValidJson(string $string): bool
    {
        try {
            json_decode($string, true, 512, JSON_THROW_ON_ERROR);

            return true;
        } catch (JsonException $e) {
            return false;
        }
    }
}
