<?php

namespace App\Providers;

use App\Broadcasting\ExpoPushChannel;
use App\Mail\VerifyAccount;
use App\Models\User;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
use Spatie\Health\Checks\Checks\DatabaseCheck;
use Spatie\Health\Checks\Checks\DebugModeCheck;
use Spatie\Health\Checks\Checks\EnvironmentCheck;
use Spatie\Health\Checks\Checks\HorizonCheck;
use Spatie\Health\Checks\Checks\MeilisearchCheck;
use Spatie\Health\Checks\Checks\OptimizedAppCheck;
use Spatie\Health\Checks\Checks\RedisCheck;
use Spatie\Health\Checks\Checks\ScheduleCheck;
use Spatie\Health\Checks\Checks\UsedDiskSpaceCheck;
use Spatie\Health\Facades\Health;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        if ($this->app->environment('production')) {
            URL::forceScheme('https');
        }

        Notification::extend('expo', fn ($app) => $app->make(ExpoPushChannel::class));

        VerifyEmail::createUrlUsing(function (User $notifiable): string {
            $relativeUrl = URL::temporarySignedRoute(
                'verification.verify',
                now()->addMinutes((int) config('auth.verification.expire', 60)),
                [
                    'id' => $notifiable->getKey(),
                    'hash' => sha1($notifiable->getEmailForVerification()),
                ],
                absolute: false,
            );

            return url($relativeUrl);
        });

        VerifyEmail::toMailUsing(
            fn (User $notifiable, string $verificationUrl): VerifyAccount => (new VerifyAccount($notifiable, $verificationUrl))
                ->to($notifiable->getEmailForVerification())
        );

        Gate::define('viewApiDocs', function ($user = null) {
            // Option A : Autoriser tout le monde (Attention : la doc sera publique hors local)
            return true;

            /* // Option B : Autoriser seulement certains emails
            return in_array($user?->email, [
                'admin@tondomaine.com',
            ], true);
            */
        });

        Health::checks([
            DatabaseCheck::new(),
            UsedDiskSpaceCheck::new(),
            RedisCheck::new(),
            ScheduleCheck::new(),
            HorizonCheck::new(),
            OptimizedAppCheck::new(),
            EnvironmentCheck::new(),
            DebugModeCheck::new(),
            MeilisearchCheck::new()
                ->url('http://meilisearch:7700/health'),

        ]);
    }
}
