<?php

namespace App\Providers;

use App\Support\Safety\DestructiveDbGuard;
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        if (app()->environment('production') && (bool) config('app.debug')) {
            Log::warning('APP_DEBUG is enabled in production environment. Disable debug mode for production deployments.');
        }

        Event::listen(CommandStarting::class, function (CommandStarting $event): void {
            $commandName = is_string($event->command)
                ? $event->command
                : ($event->input?->getFirstArgument() ?? null);

            try {
                app(DestructiveDbGuard::class)->check($commandName);
            } catch (\Throwable $exception) {
                if (isset($event->output) && $event->output) {
                    $event->output->writeln("<error>{$exception->getMessage()}</error>");
                } else {
                    Log::error($exception->getMessage());
                }

                throw $exception;
            }
        });
    }
}
