<?php

namespace Shm\ShmAdmin\AdminRPC;

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

class AdminRPCTCompanyUpdate
{
    public static function rpc()
    {

        return ShmRPC::lazy(function () {

            return [
                'type' => TNominalCompanies::structure(),
                'args' => Shm::structure([
                    ...TNominalCompanies::editableFields(),
                ]),
                'resolve' => function ($root, $args) {



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




                    $company = TNominalCompanies::structure()->findOne([
                        'owner' => Auth::getAuthID(),
                        'ownerCollection' =>  Auth::getAuthCollection(),
                    ]);
                    if (!$company) {
                        TNominalCompanies::structure()->insertOne([
                            'owner' => Auth::getAuthID(),
                            'ownerCollection' =>  Auth::getAuthCollection(),
                            ...$args,
                        ]);
                    } else {

                        //Редактируем если статус черновик
                        if ($company['status'] != 'draft') {
                            Shm::error("Вы не можете редактировать данные компании, так как она уже была отправлена на проверку");
                        }

                        TNominalCompanies::structure()->updateOne([
                            '_id' => $company['_id'],
                        ], [
                            '$set' => $args,
                        ]);
                    }




                    return TNominalCompanies::structure()->find([
                        'owner' => Auth::getAuthID(),
                        'ownerCollection' =>  Auth::getAuthCollection(),
                    ]);
                }

            ];
        });
    }
}