<?php

namespace Shm\ShmAdmin\AdminRPC;

use Shm\Shm;
use Shm\ShmAdmin\AdminPanel;
use Shm\ShmAuth\Auth;
use Shm\ShmChat\SchemaChat\ShmChannels;
use Shm\ShmDB\mDB;
use Shm\ShmRPC\ShmRPC;
use Shm\ShmUtils\I18n;

class AdminRPCChannels
{
    public static function rpc()
    {
        return ShmRPC::lazy(function () {
            return [
                'type' => Shm::arrayOf(ShmChannels::structure()),
                'args' => Shm::structure([
                    'collection' => Shm::nonNull(Shm::string()),
                    'ids' => Shm::nonNull(Shm::arrayOf(Shm::string())),
                ]),
                'resolve' => function ($root, $args) {
                    Auth::authenticateOrThrow(...AdminPanel::$authStructures);

                    if (!isset($args['collection'])) {
                        Shm::error(I18n::get('data_not_available_for_view'));
                    }

                    $structure = AdminPanel::fullSchema()->findItemByCollection($args['collection']);

                    if (!$structure) {
                        Shm::error(I18n::get('data_not_available_for_view'));
                    }

                    $_ids = array_map(function ($id) {
                        return mDB::id($id);
                    }, $args['ids']);

                    if (count($_ids) === 0) {
                        return [];
                    }

                    //Оставляем только те id который доступны текущему пользователю

                    $ids = $structure->aggregate([
                        [
                            '$match' => [
                                '_id' => ['$in' => $_ids],
                            ],
                        ],
                        [
                            '$group' => [
                                '_id' => null,
                                'ids' => ['$push' => '$_id'],

                            ],
                        ]
                    ])->toArray()[0]['ids'] ?? [];

                    if (count($ids) === 0) {
                        return [];
                    }

                    //Получаем каналы где references.documentId входит в $ids и references.documentCollection входит в $args['collection']
                    $channels = ShmChannels::structure()->aggregate([
                        [
                            '$match' => [
                                'references.documentId' => ['$in' => $ids],
                                'references.documentCollection' => $args['collection'],
                            ],
                        ],
                    ])->toArray();
                    return $channels;
                },
            ];
        });
    }
}