<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * Typically, users are redirected here after authentication.
     *
     * @var string
     */
    public const HOME = '/dashboard';

    /**
     * Define your route model bindings, pattern filters, and other route configuration.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->bind('dateStart', function ($dateStart) {
            $carbonDate = Carbon::createFromFormat('Y-m-d', $dateStart);
            if ($carbonDate->format('Y-m-d') === $dateStart) {
                return $carbonDate;
            }
            throw new NotFoundHttpException();
        });

        $this->bind('dateEnd', function ($dateEnd) {
            $carbonDate = Carbon::createFromFormat('Y-m-d', $dateEnd);
            if ($carbonDate->format('Y-m-d') === $dateEnd) {
                return $carbonDate;
            }
            throw new NotFoundHttpException();
        });

        $this->routes(function () {
            $this->mapApiRoutes();
        });
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });
    }

    protected function centralDomains(): array
    {
        return config('tenancy.central_domains');
    }

    protected function mapApiRoutes()
    {
        foreach ($this->centralDomains() as $domain) {
            Route::prefix('api')
                ->domain($domain)
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));
        }
    }
}
