<?php

namespace Modules\Mall\Providers;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use Modules\Mall\Http\Middleware\Authenticate;
use Modules\Mall\Http\Middleware\ShopOwner;

class MallServiceProvider extends ServiceProvider
{

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

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

    /**
     * 路由中间件
     * @var array
     */
    protected array $routeMiddleware = [
        'agent.auth'  => Authenticate::class,
        'agent.owner' => ShopOwner::class,
    ];

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

        if ($this->app->runningInConsole()) {
            $this->publishes([module_path($this->moduleName, 'Database/Seeders') => database_path('seeders')]);
        }
    }

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

        $this->app->register(RouteServiceProvider::class);

        $this->app->singleton('workflow', function ($app) {
            return new WorkflowRegistry($app['config']->get('mall.workflow'));
        });

        $viewPath = resource_path('views/modules/' . $this->moduleNameLower);

        $sourcePath = module_path($this->moduleName, 'Resources/views');

        $this->publishes([
            $sourcePath => $viewPath,
        ], 'views');

        $this->loadViewsFrom(array_merge(array_map(function ($path) {
            return $path . '/modules/' . $this->moduleNameLower;
        }, Config::get('view.paths')), [$sourcePath]), $this->moduleNameLower);

        foreach ($this->routeMiddleware as $key => $middleware) {
            Route::aliasMiddleware($key, $middleware);
        }
    }

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

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

}
