<?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\ShmTypes\CompositeTypes\VizType\VizType;
use Shm\ShmUtils\I18n;
use Shm\ShmUtils\Response;
use Shm\ShmUtils\ShmManticore;
use ShmAuditLog\ShmAuditLog;

class AdminRPCDataViz
{
    public static function rpc()
    {

        return ShmRPC::lazy(function () {

            return [
                'type' => Shm::viz(),
                'args' => [
                    'viz' => Shm::nonNull(Shm::string()),

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

                    'search' => Shm::string()->default(''),
                    'filter' => Shm::mixed(),
                    'pipeline' => Shm::mixed(),


                ],

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

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

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

                    if (!$structure) {
                        ShmRPC::error(I18n::get('data_not_available'));
                    }


                    $viz = $structure->findItemByKey($args['viz']);


                    if (!$viz || $viz->type !== 'viz') {
                        ShmRPC::error(I18n::get('viz_not_found'));
                    }

                    if ($viz instanceof VizType) {

                        $pipeline = $structure->getPipeline();



                        if (isset($args['filter'])) {



                            $pipelineFilter =  $structure->filterToPipeline($args['filter']);





                            if ($pipelineFilter) {

                                $pipeline = [
                                    ...$pipeline,
                                    ...$pipelineFilter,
                                ];
                            }
                        };

                        if (isset($args['pipeline'])) {

                            $args['pipeline'] = mDB::replaceStringToObjectIds($args['pipeline']);
                            $pipeline = [
                                ...$pipeline,
                                ...$args['pipeline'],
                            ];
                        }


                        if (isset($args['search'])) {




                            $pipeline[] = ShmManticore::getPipeline($args['collection'], $args['search']);
                        }



                        return $viz->callVizResolver($pipeline);
                    } else {
                        ShmRPC::error(I18n::get('viz_not_found'));
                    }
                }
            ];
        });
    }
}
