<?php

namespace Shm\ShmAdmin\AdminRPC;

use Shm\Shm;
use Shm\ShmAdmin\AdminPanel;
use Shm\ShmAuth\Auth;
use Shm\ShmRPC\ShmRPC;
use Shm\ShmTypes\CompositeTypes\BalanceTypes\BalanceType;
use Shm\ShmUtils\I18n;

class AdminRPCGeneratePaymentLink
{
    public static function rpc()
    {

        return ShmRPC::lazy(function () {

            return [
                'type' => Shm::string(),
                'args' => Shm::structure([
                    'currency' =>  Shm::nonNull(Shm::string()),
                    'gateway' => Shm::nonNull(Shm::string()),
                    'amount' => Shm::nonNull(Shm::float()),
                ]),
                'resolve' => function ($root, $args) {
                    Auth::authenticateOrThrow(...AdminPanel::$authStructures);

                    $findStructure = AdminPanel::findCurrentAuthStructure();

                    if (!$findStructure) {
                        Shm::error(I18n::get('error_payment'));
                    }

                    $amount = $args['amount'] ?? 0;
                    $currency = $args['currency'] ?? null;

                    if ($amount <= 0) {
                        Shm::error(I18n::get('amount_must_be_positive'));
                    }


                    $paymentItems = $findStructure->findItemsByCondition(function ($item) use ($currency) {
                        if ($item instanceof BalanceType) {


                            if ($item->currency == $currency) {
                                return true;
                            }
                        }
                        return false;
                    });

                    $paymentItem = $paymentItems[0] ?? null;

                    if (!$paymentItem) {
                        Shm::error(I18n::get('payment_currency_not_supported'));
                    }

                    if ($paymentItem instanceof BalanceType) {
                        $gateway = $paymentItem->getGateway($args['gateway']);
                        if (!$gateway) {
                            Shm::error(I18n::get('payment_gateway_not_supported'));
                        }
                        return $gateway->generatePaymentLink(Auth::getAuthID(), $amount);
                    } else {
                        Shm::error(I18n::get('payment_item_not_supported'));
                    }
                }
            ];
        });
    }
}
