<?php

namespace App\Listeners;

use App\Models\User;
use App\Notifications\ErrorNotification;
use Illuminate\Log\Events\MessageLogged;

class NotifyDeveloperOnError
{
    /** @var list<string> */
    protected array $notifyLevels = ['error', 'critical', 'alert', 'emergency'];

    public function handle(MessageLogged $event): void
    {
        if (! in_array($event->level, $this->notifyLevels)) {
            return;
        }

        $developers = User::role('Developer')->where('is_active', true)->get();

        if ($developers->isEmpty()) {
            return;
        }

        $title = '[ERROR] '.config('app.name');
        $body = $this->formatBody($event);

        foreach ($developers as $developer) {
            $developer->notifications()->create([
                'title' => $title,
                'body' => $body,
            ]);

            $developer->notify(new ErrorNotification(
                title: $title,
                body: $body,
                level: $event->level,
            ));
        }
    }

    protected function formatBody(MessageLogged $event): string
    {
        $message = $event->message;

        if (isset($event->context['exception'])) {
            $exception = $event->context['exception'];
            $message .= ' - '.get_class($exception).': '.$exception->getMessage();
        }

        return $message;
    }
}
