<?php

namespace Shm\ShmAdmin\AdminRPC;

use Shm\Shm;
use Shm\ShmAdmin\AdminPanel;
use Shm\ShmAuth\Auth;
use Shm\ShmDB\mDB;
use Shm\ShmRPC\ShmRPC;
use Shm\ShmSocial\ShmSocials;
use Shm\ShmUtils\I18n;
use Shm\ShmUtils\Response;
use Shm\ShmUtils\ShmManticore;

class AdminRPCSocials
{
    public static function rpc()
    {

        return ShmRPC::lazy(function () {

            return [
                'type' => Shm::arrayOf(ShmSocials::structure()),
                'args' => Shm::structure([

                    "_id" => Shm::ID()->default(null),

                    "collection" => Shm::nonNull(Shm::string()),

                ]),
                'resolve' => function ($root, $args) {



                    Auth::authenticateOrThrow(...AdminPanel::$authStructures);

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


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


                    $item =  $structure->aggregate([
                        [
                            '$match' => [
                                '_id' => mDB::id($args['_id']),
                            ],
                        ]
                    ])->toArray()[0] ?? null;

                    if (!$item) {

                        return [];
                    }


                    return  ShmSocials::structure()->find([
                        'owner' => $item['_id'],
                        'ownerCollection' =>  $structure->collection,
                    ]);
                }

            ];
        });
    }
}
