<?php
declare(strict_types=1);

namespace App\Notifications;

use App\Support\CoreHooks;
use App\Support\Hooks;
use Throwable;

/** Trusted-plugin extension registry for outbound notification channels. */
final class NotificationChannelRegistry
{
    /** @return array<string,array<string,mixed>> */
    public function all(): array
    {
        $core = [
            'database' => ['label' => 'Database', 'core' => true],
            'email' => ['label' => 'Email', 'core' => true],
            'telegram' => ['label' => 'Telegram', 'core' => true],
        ];
        $filtered = Hooks::filter(CoreHooks::NOTIFICATION_CHANNELS, $core, []);
        if (!is_array($filtered)) return $core;

        $safe = $core;
        foreach ($filtered as $slug => $definition) {
            $slug = strtolower(trim((string) $slug));
            if (preg_match('/^[a-z][a-z0-9_]{1,63}$/', $slug) !== 1 || !is_array($definition)) continue;
            if (isset($core[$slug])) {
                $safe[$slug] = $core[$slug];
                continue;
            }
            if (!is_callable($definition['send'] ?? null)) continue;
            $safe[$slug] = [
                'label' => trim((string) ($definition['label'] ?? $slug)) ?: $slug,
                'core' => false,
                'send' => $definition['send'],
                'enabled_setting' => trim((string) ($definition['enabled_setting'] ?? 'notifications.channel_' . $slug . '_enabled')),
            ];
        }
        return $safe;
    }

    /** @param array<string,mixed> $message */
    public function sendCustom(string $channel, array $message): bool
    {
        $channel = strtolower(trim($channel));
        $definition = $this->all()[$channel] ?? null;
        if (!is_array($definition) || !empty($definition['core']) || !is_callable($definition['send'] ?? null)) return false;
        try {
            return (bool) ($definition['send'])($message);
        } catch (Throwable) {
            return false;
        }
    }
}
