<?php

namespace App\Providers;

use App\Infrastructure\Health\InfrastructureChecker;
use App\Support\DevelopmentDatabaseGuard;
use Illuminate\Database\Console\Migrations\FreshCommand;
use Illuminate\Database\Console\Migrations\RefreshCommand;
use Illuminate\Database\Console\WipeCommand;
use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\URL;
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 ($rootUrl = config('app.url')) {
            URL::forceRootUrl($rootUrl);
        }

        $this->prohibitDestructiveDatabaseCommandsOnDev();

        Event::listen(DiagnosingHealth::class, function (): void {
            app(InfrastructureChecker::class)->run();
        });
    }

    private function prohibitDestructiveDatabaseCommandsOnDev(): void
    {
        if ($this->app->environment('testing')) {
            return;
        }

        $connection = (string) config('database.default');
        $database = (string) config("database.connections.{$connection}.database");

        $shouldProhibit = DevelopmentDatabaseGuard::isProtectedDatabase($connection, $database)
            && ! DevelopmentDatabaseGuard::destructiveOperationsAllowed();

        if (! $shouldProhibit) {
            return;
        }

        FreshCommand::prohibit();
        RefreshCommand::prohibit();
        WipeCommand::prohibit();
    }
}
