<?php

namespace Yjtec\YLQR\Console;

use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;

class LqrInitCommand extends Command
{
    protected $signature = 'lqr:init';

    protected $description = 'lqr init';

    /**
     * @param RabbitMQConnector $connector
     * @throws Exception
     */
    public function handle(): void
    {
        //如果交换机不存在,声明交换机
        $config  = config('queue.connections.lqr');
        $queue   = Arr::get($config, 'queue', 'default');
        $options = Arr::get($config, 'options');
        $exchange = Arr::get($options['queue'], 'exchange');
        $this->call('rabbitmq:exchange-declare', [
            'name'      => $exchange,
            '--type'    => Arr::get($options['queue'], 'exchange_type'),
            '--durable' => 0,
        ]);
        //如果队列不存在,创建队列
        $this->call('rabbitmq:queue-declare', [
            'name' => $queue,
        ]);

        //判断是否包含keys,如果包含直接绑定到队列
        $keys = config('lrouter.keys');
        if ($keys) {
            foreach ($keys as $key) {
                $this->call('rabbitmq:queue-bind', [
                    'queue'         => $queue,
                    'exchange'      => $exchange,
                    '--routing-key' => sprintf(Arr::get($options['queue'],'exchange_routing_key'),$key),
                ]);
            }
        }
    }
}