<?php
namespace EasyChat\Library\Ai;

use EasyChat\Model\Messenger;








class ConnectedChannelIdentityGuard {

    private $registry;
    private $model_messenger;

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

    public function check(array $chat): array {
        $provider = $this->normalizeProvider((string)($chat['source_provider'] ?? ''));
        if (!in_array($provider, ['max', 'max-bot'], true)) {
            return $this->allowed();
        }

        $channel_id = (int)($chat['source_channel_id'] ?? 0);
        $contact_id = (int)($chat['external_contact_id'] ?? 0);
        if ($channel_id <= 0 || $contact_id <= 0) {
            return $this->allowed();
        }

        try {
            $model_messenger = $this->messengerModel();
            $contact = $model_messenger->getContactById($contact_id);
            $sender_id = trim((string)($contact['external_user_id'] ?? ''));
            if ($sender_id === '') {
                return $this->allowed();
            }

            foreach ($model_messenger->listChannels(['max', 'max-bot', 'max_bot']) as $channel) {
                $candidate_channel_id = (int)($channel['channel_id'] ?? 0);
                if ($candidate_channel_id <= 0 || $candidate_channel_id === $channel_id) {
                    continue;
                }
                if ((string)($channel['status'] ?? '') !== 'active') {
                    continue;
                }

                foreach (['bot_user_id', 'external_account_id'] as $identity_field) {
                    $connected_id = trim((string)($channel[$identity_field] ?? ''));
                    if ($connected_id !== '' && hash_equals($connected_id, $sender_id)) {
                        return [
                            'blocked' => true,
                            'reason' => 'connected_channel_identity',
                            'matched_provider' => $this->normalizeProvider((string)($channel['provider'] ?? '')),
                        ];
                    }
                }
            }
        } catch (\Throwable $e) {
             
             
            return $this->allowed('identity_check_unavailable');
        }

        return $this->allowed();
    }

    private function messengerModel() {
        if ($this->model_messenger === null) {
            $this->model_messenger = new Messenger($this->registry);
        }

        return $this->model_messenger;
    }

    private function normalizeProvider(string $provider): string {
        $provider = strtolower(trim($provider));
        return $provider === 'max_bot' ? 'max-bot' : $provider;
    }

    private function allowed(string $detail = ''): array {
        return [
            'blocked' => false,
            'reason' => $detail,
            'matched_provider' => '',
        ];
    }
}
