<?php

namespace Kylin\Payment\Services;

use Kylin\Payment\Jobs\PayJob;
use Kylin\Payment\Jobs\RefundJob;
use Kylin\Payment\Jobs\CloseJob;
use Kylin\Payment\Jobs\QueryJob;
use Illuminate\Contracts\Container\Container;
use Illuminate\Foundation\Bus\PendingDispatch;

/**
 * 队列服务类
 */
class QueueService
{
    /**
     * 构造函数
     */
    public function __construct(
        protected readonly Container $app
    ) {
    }

    /**
     * 异步执行支付
     */
    public function pay(string $type, array $params, string $name = 'default', ?string $queue = null): PendingDispatch
    {
        $job = new PayJob($type, $params, $name);

        if ($queue) {
            return $job->onQueue($queue)->dispatch();
        }

        return $job->dispatch();
    }

    /**
     * 异步执行退款
     */
    public function refund(string $type, array $params, string $name = 'default', ?string $queue = null): PendingDispatch
    {
        $job = new RefundJob($type, $params, $name);

        if ($queue) {
            return $job->onQueue($queue)->dispatch();
        }

        return $job->dispatch();
    }

    /**
     * 异步执行关闭订单
     */
    public function close(string $type, string $orderNo, string $name = 'default', ?string $queue = null): PendingDispatch
    {
        $job = new CloseJob($type, $orderNo, $name);

        if ($queue) {
            return $job->onQueue($queue)->dispatch();
        }

        return $job->dispatch();
    }

    /**
     * 异步执行查询订单
     */
    public function query(string $type, string $orderNo, string $name = 'default', ?string $queue = null): PendingDispatch
    {
        $job = new QueryJob($type, $orderNo, $name);

        if ($queue) {
            return $job->onQueue($queue)->dispatch();
        }

        return $job->dispatch();
    }
}
