<?php

namespace App\Filament\Resources\RoleResource\Pages;

use App\Filament\Resources\RoleResource;
use App\Models\Role;
use App\Services\AuditLog;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Auth;

class CreateRole extends CreateRecord
{
    protected static string $resource = RoleResource::class;

    /** @var array<int, string> */
    protected array $permissionNames = [];

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        // Livewire syncs an all-unchecked PermissionPicker back as `false`
        // rather than `[]` — `?? []` alone doesn't catch that, and assigning
        // it to this typed array property would otherwise throw.
        $this->permissionNames = is_array($data['permissions'] ?? null) ? $data['permissions'] : [];
        unset($data['permissions']);

        // A role created through the UI is never system-defined or full-admin
        // — matches RoleController::store(), which hardcodes both to false.
        $data['is_system'] = false;
        $data['is_full_admin'] = false;
        $data['created_by'] = Auth::id();
        $data['updated_by'] = Auth::id();

        return $data;
    }

    protected function afterCreate(): void
    {
        /** @var Role $role */
        $role = $this->record;

        $role->permissions()->sync(RoleResource::permissionIdsFor($this->permissionNames));

        AuditLog::record('role.created', $role, [
            'name' => $role->name,
            'permissions_count' => count($this->permissionNames),
            'permissions' => $this->permissionNames,
        ]);
    }
}
