<?php

namespace Maestro\Core;

use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use Maestro\Core\Console\Commands\InstallCommand;
use Maestro\Core\Console\Commands\StatusCommand;
use Maestro\Core\Console\Commands\UpdateCommand;
use Spatie\Permission\Middleware\PermissionMiddleware;
use Spatie\Permission\Middleware\RoleMiddleware;

class MaestroServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->mergeConfigFrom(__DIR__.'/../config/maestro.php', 'maestro');

        if ($this->app->runningInConsole()) {
            $this->commands([
                InstallCommand::class,
                UpdateCommand::class,
                StatusCommand::class,
            ]);
        }
    }

    public function boot(): void
    {
        $this->loadMigrationsFrom(__DIR__.'/../database/migrations');

        $this->publishes([
            __DIR__.'/../config/maestro.php' => config_path('maestro.php'),
        ], 'maestro-config');

        // Override auth model so Spatie permission works correctly
        config(['auth.providers.users.model' => \Maestro\Core\Models\User::class]);

        // Register Spatie middleware aliases
        $this->app['router']->aliasMiddleware('permission', PermissionMiddleware::class);
        $this->app['router']->aliasMiddleware('role', RoleMiddleware::class);

        $this->registerRoutes();
    }

    protected function registerRoutes(): void
    {
        Route::middleware(['web'])
            ->prefix('api')
            ->name('maestro.api.')
            ->group(__DIR__.'/../routes/api.php');
    }
}
