<?php
namespace EasyChat\Library\Messenger;

class MaxInboundScope {

    const DIALOGS = 'dialogs';
    const CHANNELS = 'channels';
    const GROUPS = 'groups';

    private const ALLOWED_SCOPE = [self::DIALOGS, self::CHANNELS, self::GROUPS];
    private const DEFAULT_SCOPE = [self::DIALOGS];

    public static function normalize($value): array {
        if (is_string($value)) {
            $decoded = json_decode($value, true);
            if (is_array($decoded)) {
                $value = $decoded;
            } else {
                $value = preg_split('/[,\s]+/', $value);
            }
        }

        if (!is_array($value)) {
            return self::DEFAULT_SCOPE;
        }

        $allowed = array_fill_keys(self::ALLOWED_SCOPE, true);
        $result = [];
        foreach ($value as $item) {
            $item = strtolower(trim((string)$item));
            if (isset($allowed[$item])) {
                $result[$item] = $item;
            }
        }

        return $result ? array_values($result) : self::DEFAULT_SCOPE;
    }

    public static function fromSettings(array $settings): array {
        return self::normalize($settings['personal_inbound_scope'] ?? self::DEFAULT_SCOPE);
    }

    public static function fromPost($value): array {
        return self::normalize(is_array($value) ? $value : []);
    }

    public static function directionForChatType(string $chat_type): string {
        $chat_type = strtoupper(trim($chat_type));
        if ($chat_type === 'DIALOG') {
            return self::DIALOGS;
        }
        if ($chat_type === 'CHANNEL') {
            return self::CHANNELS;
        }
        if ($chat_type === 'CHAT') {
            return self::GROUPS;
        }
         
         
        return '';
    }

    public static function isAcceptedChatType(string $chat_type, array $scope): bool {
        $direction = self::directionForChatType($chat_type);
        return $direction !== '' && in_array($direction, self::normalize($scope), true);
    }
}
