<?php declare(strict_types=1);

namespace Diamond\Infrastructure\Logging;

use Monolog\DateTimeImmutable;

class DuplicateQueryLogger extends \Monolog\Logger
{
    private array $queries = [];

    public function addRecord(int $level, string $message, array $context = [], ?DateTimeImmutable $datetime = null): bool
    {
        if(preg_match('~Memory\sPeak:.*?\|(.*?)$~is',$message,$match)){
            $sql = $match[1];
            if (!isset($this->queries[$sql])) {
                $this->queries[$sql] = 0;
            }

            $this->queries[$sql]++;
        }

        return parent::addRecord($level, $message, $context);
    }

    public function getDuplicateQueries(): array
    {
        return array_filter($this->queries, function ($count) {
            return $count > 1;
        });
    }
}