<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Inertia\Middleware;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that is loaded on the first page visit.
     *
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determine the current asset version.
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    /**
     * Define the props that are shared by default.
     *
     * @return array<string, mixed>
     */
    public function share(Request $request): array
    {

        return [
            ...parent::share($request),
            'logo_api_url' => config('app.logo_api_url'),
            'auth' => [
                'user' => $request->user(),
                'roles' => $request->user()?->getRoleNames() ?? [],
                'permissions' => $request->user()?->getAllPermissions()->pluck('name') ?? [],
                'apiToken' => session('api_token'),
            ],
            'flash' => [
                'success' => $request->session()->get('success'),
                'error'   => $request->session()->get('error'),
            ],
            'achievement_notifications' => fn() => $request->user()
                ? $request->user()
                    ->notifications()
                    ->with('achievement')
                    ->where('is_achievement', true)
                    ->whereNull('read_at')
                    ->latest()
                    ->get()
                : [],
            'unread_notification_count' => $request->user()?->notifications()
                ->whereNull('read_at')
                ->whereNull('expires_at')
                ->orWhere('expires_at', '>', now())
                ->count(),
        ];
    }
}
