<?php

namespace Daylight\Core\Modules\Multilingualism;

use Illuminate\Auth\Middleware\Authenticate;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;

class MultilingualismServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        Redirector::macro('translatedRoute', function ($route, $parameters = [], $status = 302, $headers = []) {
            return redirect(route(app()->getLocale() . '_' . $route, $parameters), $status, $headers);
        });

        UrlGenerator::macro('temporarySignedTranslatedRoute', function ($name, $expiration, $parameters = [], $absolute = true) {
            return $this->temporarySignedRoute(app()->getLocale() . '_' . $name, $expiration, $parameters, $absolute);
        });

        VerifyEmail::createUrlUsing(function ($notifiable) {
            return URL::temporarySignedTranslatedRoute(
                'verification.verify',
                Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
                [
                    'id' => $notifiable->getKey(),
                    'hash' => sha1($notifiable->getEmailForVerification()),
                ]
            );
        });

        Authenticate::redirectUsing(function () {
            return translatedRoute('login');
        });

        Request::macro('translatedRouteIs', function ($route) {
            return $this->routeIs(app()->getLocale() . '_' . $route);
        });
    }

    public function boot(): void
    {
        Carbon::setlocale(app()->getLocale());

        if (Multilingualism::getAvailableLocales()->contains(request()->segment(1))) {
            App::setLocale(request()->segment(1));

            config([
                'multilingualism.locale_prefix' => request()->segment(1),
            ]);
        }
    }
}
