<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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,
            ]);
        }
    }
}
