<?php

namespace Velis\Log\Sentry;

use Sentry\Breadcrumb;
use Sentry\SentrySdk;

/**
 * @author Szymon Janaczek <szymon.janaczek@singu.com>
 */
final class BreadcrumbHelper
{
    public function add(Breadcrumb $breadcrumb): void
    {
        SentrySdk::getCurrentHub()->addBreadcrumb($breadcrumb);
    }

    public function addSqlQuery(string $sql, array $params = [], array $details = []): void
    {
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
        array_splice($trace, 0, 1);
        $details['trace'] = $trace;

        $breadcrumb = new Breadcrumb(
            level: Breadcrumb::LEVEL_INFO,
            type: Breadcrumb::TYPE_DEFAULT,
            category: 'sql.query',
            message: $sql,
            metadata: ['params' => $params] + $details
        );

        $this->add($breadcrumb);
    }

    public function addLog($record, array $details = []): void
    {
        $allowedLevels = ['error', 'debug', 'info', 'warning', 'error', 'fatal'];
        $level = strtolower($record['level_name']);
        if (!in_array($level, $allowedLevels)) {
            $level = 'fatal';
        }

        $breadcrumb = new Breadcrumb(
            level: $level,
            type: Breadcrumb::TYPE_DEFAULT,
            category: $record['channel'],
            message: $record['message'],
            metadata: array_filter([
                'context' => $record['context'],
                'extra' => $record['extra'],
            ]) + $details,
        );

        $this->add($breadcrumb);
    }
}
