<?php

namespace Shm\ShmAdmin\AdminRPC;

use Shm\Shm;
use Shm\ShmAdmin\AdminPanel;
use Shm\ShmAuth\Auth;
use Shm\ShmAuth\AuthApiKey;
use Shm\ShmRPC\ShmRPC;
use Shm\ShmUtils\I18n;
use Shm\ShmUtils\Response;

class AdminRPCNewApiKey
{
    public static function rpc()
    {

        return ShmRPC::lazy(function () {

            return [
                'type' => Shm::string(),
                'resolve' => function ($root, $args) {

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

                    $title = $args['title'] ?? null;

                    if (!$title) {
                        Response::validation(I18n::get('api_key_name_required'));
                    }


                    $AuthApiKey = new AuthApiKey();
                    $AuthApiKey->structure(AdminPanel::$authStructures[0]);
                    $AuthApiKey->userId(Auth::getAuthID());
                    $AuthApiKey->payload([]);
                    $apikey = $AuthApiKey->generate();

                    if (!$apikey) {
                        Response::validation(I18n::get('api_key_create_error'));
                    }

                    return   $apikey;
                }

            ];
        });
    }
}
