<?php

namespace App\Providers;

use App\Support\DealerBranding\DealerBrandingResolver;
use App\Support\Safety\DestructiveDbGuard;
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;
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;
            }
        });

        View::composer(['layouts.*', 'settings.branding.*'], function ($view): void {
            $data = $view->getData();
            $dealerFromView = $data['dealer'] ?? null;

            $resolved = app(DealerBrandingResolver::class)->resolve($dealerFromView instanceof \App\Models\Dealer ? $dealerFromView : null);
            $cssVars = (array) ($resolved['css_vars'] ?? []);

            $style = collect($cssVars)
                ->map(fn ($value, $key) => $key.': '.$value.';')
                ->implode(' ');

            $view->with([
                'dealerBranding' => $resolved,
                'dealerBrandingCssVars' => $style,
                'dealerLogoUrl' => data_get($resolved, 'assets.logo_url'),
                'dealerFaviconUrl' => data_get($resolved, 'assets.favicon_url'),
            ]);
        });
    }
}
