<?php

namespace Modules\Identity\Filament\Resources\Staff;

use App\Models\User;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Modules\Identity\Filament\Resources\Staff\Pages\CreateStaff;
use Modules\Identity\Filament\Resources\Staff\Pages\EditStaff;
use Modules\Identity\Filament\Resources\Staff\Pages\ListStaff;
use Modules\Identity\Filament\Resources\Staff\Schemas\StaffForm;
use Modules\Identity\Filament\Resources\Staff\Tables\StaffTable;
use UnitEnum;

/**
 * Staff and Customer both read from the single `users` table (domain.md §4
 * — no separate tables, no auth-guard split); this resource scopes to users
 * carrying an admin-tier role, the same set that can sign in to this panel
 * at all (User::ADMIN_TIER_ROLES). Gated by manage_staff — deliberately
 * separate from manage_roles (T7.x follow-up decision): granting someone
 * access to the panel is a different, more sensitive action than editing
 * what a role can do.
 */
class StaffResource extends Resource
{
    protected static ?string $model = User::class;

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedUserGroup;

    protected static string|UnitEnum|null $navigationGroup = 'Access';

    protected static ?string $navigationLabel = 'Staff';

    protected static ?string $modelLabel = 'Staff Member';

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->role(User::ADMIN_TIER_ROLES);
    }

    public static function form(Schema $schema): Schema
    {
        return StaffForm::configure($schema);
    }

    public static function table(Table $table): Table
    {
        return StaffTable::configure($table);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListStaff::route('/'),
            'create' => CreateStaff::route('/create'),
            'edit' => EditStaff::route('/{record}/edit'),
        ];
    }

    public static function canViewAny(): bool
    {
        return auth()->user()?->can('manage_staff') ?? false;
    }

    public static function canCreate(): bool
    {
        return auth()->user()?->can('manage_staff') ?? false;
    }

    public static function canEdit(Model $record): bool
    {
        return auth()->user()?->can('manage_staff') ?? false;
    }

    /**
     * Blocks the one obviously destructive foot-gun (a staff member
     * deleting their own account and locking themselves out) on top of the
     * manage_staff permission check.
     */
    public static function canDelete(Model $record): bool
    {
        return (auth()->user()?->can('manage_staff') ?? false)
            && auth()->id() !== $record->getKey();
    }
}
