<?php

declare(strict_types=1);

namespace TechnoArtisan\FilamentCms;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\URL;
use ReflectionException;
use Spatie\Honeypot\Events\SpamDetectedEvent;
use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;
use TechnoArtisan\FilamentCms\Commands\CacheAllCommand;
use TechnoArtisan\FilamentCms\Commands\SitemapGeneratorCommand;
use TechnoArtisan\FilamentCms\Configs\Localization as LocalizationConfig;
use TechnoArtisan\FilamentCms\Listeners\HandleSpamDetect;
use function var_export;

class FilamentCmsServiceProvider extends PackageServiceProvider
{
    public function configurePackage(Package $package): void
    {
        /*
         * More info: https://github.com/spatie/laravel-package-tools
         */
        $package
            ->name(FilamentCms::getPackageName())
            ->hasConfigFile()
            ->hasRoutes('web')
            ->hasTranslations()
            ->hasViews()
            ->discoversMigrations()
            ->hasCommands([
                CacheAllCommand::class,
                SitemapGeneratorCommand::class,
            ])
            ->hasAssets();
    }

    /**
     * @throws ReflectionException
     */
    public function packageRegistered(): void
    {
        parent::packageRegistered();

        app()->bind(LocalizationConfig::class, fn() => new LocalizationConfig(
            config('filament-cms.route_config.variable'),
            config('filament-cms.route_config.segment'),
            config('filament-cms.locale.available'),
            config('filament-cms.locale.fallback')
        ));
    }

    public function packageBooted(): void
    {
        parent::packageBooted();

        Event::listen(
            SpamDetectedEvent::class, // event
            HandleSpamDetect::class,  // handler
        );

        // for configured stages force ssl
        if (in_array(app()->environment(), config('filament-cms.ssl-environments'), true)) {
            URL::forceScheme('https');
        }

        $this->registerBladeDirectives();
    }

    private function registerBladeDirectives(): void
    {
    }
}
