<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service\domain\pay;

use Core\service\BaseCoreService;
use app\service\domain\pay\gateway\PaymentGatewayInterface;
use think\App;
use think\Request;

/**
 * CoreRefundOrchestrator 支付退款orchestrator类
 * Class CoreRefundOrchestrator
 * @package app\service\domain\pay
 */
class CoreRefundOrchestrator extends BaseCoreService
{
    private CorePayOrchestrator $payOrchestrator;

    /**
     * @param App $app
     * @param CorePayOrchestrator $payOrchestrator
     */
    public function __construct(App $app, CorePayOrchestrator $payOrchestrator)
    {
        parent::__construct($app);
        $this->payOrchestrator = $payOrchestrator;
    }

    /**
     * 创建退款订单
     * @param array $refund 退款信息
     * @param array $payment 支付订单信息
     * @return array 退款订单信息
     */
    public function refund(array $refund, array $payment): array
    {
        $provider = (string)($payment['pay_type'] ?? '');
        $gateway = $this->payOrchestrator->gateway($provider);

        if (!$gateway) {
            return [
                'code' => 0,
                'msg' => '',
                'status' => 2,
                'remark' => '',
                'extra' => [],
            ];
        }

        return $gateway->refund($refund, $payment);
    }

    /**
     * 处理退款通知
     * @param string $provider 退款网关提供者
     * @param string $terminal 终端
     * @param Request $request 请求
     * @return array 退款通知信息
     */
    public function refundNotify(string $provider, string $terminal, Request $request): array
    {
        $gateway = $this->payOrchestrator->gateway($provider);
        if (!$gateway) {
            throw new \RuntimeException(': ' . $provider);
        }

        return $gateway->refundNotify($request, $terminal);
    }
}
