<?php

namespace App\Providers;

use App\Models\User;
use App\Support\Tenancy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(Tenancy::class);
    }

    public function boot(): void
    {
        // Super admins bypass all permission checks.
        Gate::before(function (User $user, string $ability) {
            return $user->isSuperAdmin() ? true : null;
        });

        // Share soft-usage + unread notification count with tenant layouts.
        View::composer('layouts.app', function ($view) {
            $tenant = app(\App\Support\Tenancy::class)->get();
            $user = auth()->user();
            if ($tenant && $user) {
                $view->with('waUsage', app(\App\Domain\Subscription\UsageService::class)->status($tenant));
                $view->with('unreadCount', $user->unreadNotifications()->count());
            }
        });
    }
}
