<?php

namespace App\Filament\Resources\UserResource\Pages;

use App\Filament\Forms\Components\PermissionOverridePicker;
use App\Filament\Resources\UserResource;
use App\Models\User;
use App\Services\AuditLog;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Auth;

class CreateUser extends CreateRecord
{
    protected static string $resource = UserResource::class;

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

    /** @var array{grant: array<int, string>, revoke: array<int, string>} */
    protected array $overrides = ['grant' => [], 'revoke' => []];

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $this->roleIds = array_values(array_unique(array_map('intval', $data['role_ids'] ?? [])));
        // normalize() absorbs the shapes Livewire can send for an empty checkbox
        // group (`false`, `null`) so this typed property is always the two-list
        // array the rest of the flow expects.
        $this->overrides = PermissionOverridePicker::normalize($data['permission_overrides'] ?? null);
        unset($data['role_ids'], $data['permission_overrides']);

        $data['role_id'] = $this->roleIds[0] ?? null;
        $data['created_by'] = Auth::id();
        $data['updated_by'] = Auth::id();
        $data['email_verified_at'] = now();

        return $data;
    }

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

        $overrides = UserResource::applyRolesAndOverrides($user, $this->roleIds, $this->overrides);

        // An all-branch / full-admin user must never carry per-branch grants;
        // the warehouses picker is hidden for them, so clear anything a stale
        // form submission might have synced anyway.
        if ($user->is_all_branches || $user->isFullAdmin()) {
            $user->warehouses()->sync([]);
        }

        AuditLog::record('user.created', $user, [
            'roles' => $user->roles()->pluck('name')->all(),
            'allow_overrides' => $overrides['allow'],
            'deny_overrides' => $overrides['deny'],
        ]);
    }
}
