<?php

namespace Velis\Debugger;

use Throwable;
use Velis\Db\Db;
use Velis\Db\Exception as DbException;
use Velis\Exception;
use Velis\Log\LoggerInterface;
use Velis\Model\DataObject\NoColumnsException;

class ErrorReporter
{
    public function __construct(
        private readonly ErrorMailFactory $mailFactory,
        private readonly ?Db $db,
        private readonly LoggerInterface $dbExceptionLogger,
        private readonly LoggerInterface $logger,
    ) {
    }

    /**
     * @throws NoColumnsException
     */
    public function report(Throwable $e): void
    {
        $this->log($e);

        $mail = $this->mailFactory->createMail($e);
        $mail->send();
    }

    public function log(Throwable $e, bool $skipLegacy = false): void
    {
        // we have to keep logging in this way for the legacy system.
        if (!$skipLegacy) {
            error_log($e);
        }

        if ($e instanceof DbException) {
            $this->dbExceptionLogger
                ->error('DB Exception: ' . $e->getMessage(), [
                    'exception' => $e,
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                    'trace' => $e->getTrace(),
                    'details' => $e->toArray(),
                    'queries' => $this->db?->getExecutedQueries() ?? [],
                ])
            ;

            return;
        }

        $this->logger
            ->error('Application Exception: ' . $e->getMessage(), [
                'exception' => $e,
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTrace(),
                'queries' => $this->db?->getExecutedQueries() ?? [],
                'debugInfo' => $e instanceof Exception ? $e->getDebugInfo() : null,
            ])
        ;
    }
}
