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

class AdminRPCHash
{
    public static function rpc()
    {

        return ShmRPC::lazy(function () {

            return [
                'type' => Shm::string(),
                'args' => Shm::structure([
                    "_id" => Shm::ID(),
                    "collection" => Shm::nonNull(Shm::string()),
                    'limit' => Shm::int()->default(30),
                    'offset' =>  Shm::int()->default(0),
                    'search' => Shm::string()->default(''),
                    'sort' => Shm::structure([
                        'direction' => Shm::enum([
                            'ASC' => 'По возрастанию',
                            'DESC' => 'По убыванию',
                        ])->default('DESC'),
                        'field' => Shm::string(),
                    ]),
                    'filter' => Shm::mixed(),
                    'pipeline' => Shm::mixed(),

                ]),

                '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']);



                    if (!$structure) {
                        Response::validation(I18n::get('data_not_available_for_view'));
                    }


                    $pipeline = $structure->getPipeline();




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


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


                        if ($pipelineFilter) {

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

                    if (isset($args['pipeline'])) {
                        $pipeline = [
                            ...$pipeline,
                            ...$args['pipeline'],
                        ];
                    }



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

                        $pipeline[] =  ShmManticore::getPipeline($structure->collection, mb_strtolower(trim($args['search'])));
                    }



                    $_limit = $args['limit'] ?? null;

                    if (!$_limit) {
                        return null;
                    }







                    if (isset($args['sort']) && isset($args['sort']['field']) && isset($args['sort']['direction'])) {

                        $pipeline[] = [
                            '$sort' => [
                                $args['sort']['field'] => $args['sort']['direction'] == "DESC" ? -1 : 1,
                            ],
                        ];
                    } else {

                        if ($structure->manualSort) {

                            $pipeline[] = [
                                '$sort' => [
                                    "_sortWeight" => -1,

                                ],
                            ];
                        } else {

                            $pipeline[] = [
                                '$sort' => [
                                    "_id" => -1,
                                ],
                            ];
                        }
                    }

                    if (isset($args['offset']) && $args['offset'] > 0) {

                        $pipeline[] = [
                            '$skip' => $args['offset'],
                        ];
                    }


                    if (isset($args['_id']) && $args['_id']) {
                        $pipeline[] = [
                            '$match' => [
                                "_id" => mDB::id($args['_id']),
                            ],
                        ];
                    }



                    //Если только hash то берем максимальный updated_at
                    $pipeline[] = [
                        '$group' => [
                            '_id' => null,
                            'updated_at' => ['$max' => '$updated_at'],
                        ],
                    ];

                    $hashResult = $structure->aggregate($pipeline)->toArray();
                    $hashResult = $hashResult[0]['updated_at'] ?? "empty";
                    $hashResult = md5($hashResult);






                    return   $hashResult;
                }

            ];
        });
    }
}
