<?php

namespace App\Filament\Resources\Concerns;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

/**
 * Reproduces the source app's `can_do:{module_key}.{action}` route gate
 * (App\Http\Middleware\CheckPermission) for Filament Resources — same call
 * site (User::hasPermissionTo()), same tenant-entitlement-ceiling and
 * full-admin-bypass semantics (both already inside hasPermissionTo() via
 * App\Models\Concerns\HasPermissions), just a different place to call it
 * from. See docs/migration-plan.md §3.
 *
 * Every Resource using this trait must declare:
 *
 *   protected static string $permissionModuleKey = 'isms_products';
 *
 * matching the module_key used in permissions.md / the MenuDefinition seed.
 * Verbs beyond the CRUD ones here (.void, .export, .approve, ...) are gated
 * inline at the point of use via App\Filament\Support\Perm::can().
 */
trait HasModulePermissions
{
    public static function canViewAny(): bool
    {
        return static::hasModulePermission('access');
    }

    public static function canCreate(): bool
    {
        return static::hasModulePermission('create');
    }

    public static function canEdit(Model $record): bool
    {
        return static::hasModulePermission('edit');
    }

    public static function canDelete(Model $record): bool
    {
        return static::hasModulePermission('delete');
    }

    public static function canDeleteAny(): bool
    {
        return static::hasModulePermission('delete');
    }

    public static function canView(Model $record): bool
    {
        return static::hasModulePermission('view');
    }

    public static function shouldRegisterNavigation(): bool
    {
        return static::canViewAny();
    }

    protected static function hasModulePermission(string $action): bool
    {
        return Auth::user()?->hasPermissionTo(static::$permissionModuleKey.'.'.$action) ?? false;
    }
}
