<?php

namespace Shm\ShmAdmin\AdminRPC;

use Shm\Shm;
use Shm\ShmAdmin\AdminPanel;
use Shm\ShmAuth\Auth;
use Shm\ShmRPC\ShmRPC;
use Shm\ShmTypes\CompositeTypes\ActionType;
use Shm\ShmUtils\I18n;
use Shm\ShmUtils\Response;
use ShmAuditLog\ShmAuditLog;

class AdminRPCRunAction
{
    public static function rpc()
    {

        return ShmRPC::lazy(function () {

            return [
                'type' => Shm::structure([
                    'payload' => Shm::structure([
                        'url' => Shm::string(),
                    ]),
                ]),
                'args' => [
                    'collection' => Shm::nonNull(Shm::string()),
                    'action' => Shm::nonNull(Shm::string()),
                    'args' => 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'));
                    }


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


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

                    if ($action instanceof ActionType) {

                        $payload =  $action->callResolve($root, $args);


                        return [
                            'payload' => $payload
                        ];
                    } else {
                        ShmRPC::error(I18n::get('action_not_found'));
                    }
                }
            ];
        });
    }
}