<?php

namespace Modules\Payment\Providers;

use Illuminate\Support\ServiceProvider;
use Modules\Payment\Models\Setting;
use Yansongda\Pay\Pay;

class PaymentServiceProvider extends ServiceProvider
{

    /**
     * @var string $moduleName
     */
    protected string $moduleName = 'Payment';

    /**
     * @var string $moduleNameLower
     */
    protected string $moduleNameLower = 'payment';

    /**
     * Boot the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadMigrationsFrom(module_path($this->moduleName, 'Database/Migrations'));
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerConfig();
        $this->app->register(RouteServiceProvider::class);


        $this->app->singleton('pay.alipay', function () {
            $alipay = Setting::getDefaultConfig('alipay');

            return Pay::alipay([
                'alipay'     => [
                    'default' => $alipay,
                ],
                'logger'     => array_merge($alipay['logger'], [
                    'enable' => config('payment.logger', true),
                ]),
                'notify_url' => route('api.payment.notify.alipay')
            ]);
        });

        $this->app->singleton('pay.wechat', function () {
            $wechat = Setting::getDefaultConfig('wechat');
            return Pay::wechat([
                'wechat'     => [
                    'default' => Setting::getDefaultConfig('wechat'),
                ],
                'logger'     => array_merge($wechat['logger'], [
                    'enable' => config('payment.logger', true),
                ]),
                'notify_url' => route('api.payment.notify.alipay')
            ]);
        });

    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides(): array
    {
        return ['pay.alipay', 'pay.wechat'];
    }

    /**
     * Register config.
     *
     * @return void
     */
    protected function registerConfig()
    {
        $this->publishes([
            module_path($this->moduleName, 'Config/config.php') => config_path($this->moduleNameLower.'.php'),
        ], 'payment-config');

        $this->mergeConfigFrom(
            module_path($this->moduleName, 'Config/config.php'), $this->moduleNameLower
        );
    }

}
