<?php

namespace Tricks\LaravelTools;

use Faker\Factory;
use Faker\Generator;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Routing\Router;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Maltyxx\ImagesGenerator\ImagesGeneratorProvider;
use Sentry\Laravel\Integration;

class LaravelToolsServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        if (class_exists(Generator::class)
            && class_exists(Factory::class)
            && class_exists(ImagesGeneratorProvider::class)) {
            $this->app->singleton(Generator::class, function () {
                $faker = Factory::create();
                $faker->addProvider(ImagesGeneratorProvider::class);

                return $faker;
            });
        }
        $this->mergeConfigFrom(
            __DIR__.'/../config/laravel-tools.php', 'laravel-tools'
        );
    }

    public function boot(Router $router): void
    {
        Carbon::setLocale('de_DE');

        Model::shouldBeStrict();

        if (! app()->isLocal()) {
            Model::handleLazyLoadingViolationUsing(
                Integration::lazyLoadingViolationReporter(),
            );
            Model::handleDiscardedAttributeViolationUsing(
                Integration::lazyLoadingViolationReporter(),
            );
            Model::handleMissingAttributeViolationUsing(
                Integration::lazyLoadingViolationReporter(),
            );
        }

        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });
    }
}
