<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpAdminUsers\Pages;

use App\Filament\Resources\DberpAdminUsers\DberpAdminUserResource;
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 CreateDberpAdminUser extends CreateRecord
{
    protected static string $resource = DberpAdminUserResource::class;

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordCreation(array $data): Model
    {
        $roleIds = collect($data['role_ids'] ?? [])
            ->map(fn (mixed $roleId): int => (int) $roleId)
            ->all();

        unset($data['role_ids'], $data['password_confirmation']);

        try {
            return app(DberpAdminAccessService::class)->createUser(
                $data,
                $roleIds,
                Auth::user(),
                '管理员管理页新增管理员',
            );
        } catch (AuthorizationException $exception) {
            throw ValidationException::withMessages([
                'login_account' => $exception->getMessage(),
            ]);
        } catch (DomainException $exception) {
            $message = $exception->getMessage();
            $field = str_contains($message, '邮箱') ? 'email' : 'login_account';

            throw ValidationException::withMessages([
                $field => $message,
            ]);
        }
    }
}
