<?php
namespace EasyChat\Library\Email;

use EasyChat\Model\Setting;





final class CmsMailBridgeHealth {
    private const SETTING_KEY = 'email_cms_mail_bridge_health';
    private const MAX_AGE = 900;
    private $registry;

    public function __construct($registry) { $this->registry = $registry; }

    public function record(CmsOutboundMailBridgeInterface $bridge): array {
        $snapshot = array(
            'bridge' => $bridge->code(),
            'capabilities' => $bridge->capabilities(),
            'checked_at' => time(),
        );
        (new Setting($this->registry))->set(self::SETTING_KEY, json_encode($snapshot, JSON_UNESCAPED_SLASHES));
        return $snapshot;
    }

    public function latest(): array {
        $raw = (new Setting($this->registry))->get(self::SETTING_KEY, '');
        $snapshot = json_decode((string)$raw, true);
        if (!is_array($snapshot) || time() - (int)($snapshot['checked_at'] ?? 0) > self::MAX_AGE) return array();
        return $snapshot;
    }

    public static function supportsRequiredHeaders(array $capabilities): bool {
        foreach (array('send', 'reply_to', 'message_id', 'threading') as $capability) {
            if (empty($capabilities[$capability])) return false;
        }
        return true;
    }
}
