<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpAdminRoles\Pages;

use App\Filament\Resources\DberpAdminRoles\DberpAdminRoleResource;
use App\Filament\Resources\Pages\CreateRecord;
use App\Services\DberpAdminAccessService;
use DomainException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class CreateDberpAdminRole extends CreateRecord
{
    protected static string $resource = DberpAdminRoleResource::class;

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordCreation(array $data): Model
    {
        $permissionCodes = DberpAdminRoleResource::extractPermissionCodes($data);

        unset($data['permission_groups']);

        try {
            return app(DberpAdminAccessService::class)->createRole(
                $data,
                $permissionCodes,
                Auth::user(),
                (string) __('dberp.messages.audit_remark_admin_role_created'),
            );
        } catch (AuthorizationException|DomainException $exception) {
            throw ValidationException::withMessages([
                'display_name' => $exception->getMessage(),
            ]);
        }
    }
}
