<?php

namespace App\Filament\Resources\RoleResource\Widgets;

use App\Models\Role;
use App\Models\User;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\Auth;

/**
 * Headline figures for the Roles list — totals are TenantScope-limited
 * automatically. Mirrors the source role-management dashboard summary
 * (docs/migration-plan.md Phase 12).
 */
class RoleStatsOverview extends StatsOverviewWidget
{
    protected function getStats(): array
    {
        $total = (int) Role::query()->count();
        $active = (int) Role::query()->where('is_active', true)->count();
        $fullAdmin = (int) Role::query()->where('is_full_admin', true)->count();
        $system = (int) Role::query()->where('is_system', true)->count();
        $unassigned = (int) Role::query()
            ->whereDoesntHave('users')
            ->count();
        $usersWithRoles = (int) User::query()->whereHas('roles')->count();

        return [
            Stat::make('Total roles', (string) $total)
                ->description($active.' active'),
            Stat::make('Active', (string) $active)
                ->color('success')
                ->description('Full admin: '.$fullAdmin),
            Stat::make('System', (string) $system)
                ->description('Non-removable, seeded roles')
                ->color('gray'),
            Stat::make('Unassigned', (string) $unassigned)
                ->color($unassigned > 0 ? 'warning' : 'gray'),
            Stat::make('Users with roles', (string) $usersWithRoles)
                ->color('gray'),
        ];
    }

    public static function canView(): bool
    {
        return Auth::user()?->hasPermissionTo('user_management_roles.access') ?? false;
    }
}
