<?php

namespace Mtc\Plugins\Wisebee\Classes\Handlers;

use Mtc\Core\AdminUser;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeUser;
use Wisebee\Resources\User as RemoteUser;

class UserHandler extends BaseHandler
{
    const RESOURCE_NAME = 'user';

    const ROLE_SPECIALIST = 'specialist';

    public function handleAdminCreated(int $userID): void
    {
        /** @var AdminUser $adminUser */
        $adminUser = AdminUser::query()
            ->find($userID);

        if (empty($userID)) {
            return;
        }

        // Tries to find the user by email in Wisebee
        $remoteUsers = $this->wisebee->list(RemoteUser::class, [
            'email' => $adminUser->email,
        ]);

        if (empty($remoteUsers)) {
            $nameParts = explode(' ', $adminUser->name);

            // Create a remote user
            $remoteUser = $this->wisebee->create(RemoteUser::class, [
                'email' => $adminUser->email,
                'firstname' => $nameParts[0],
                'lastname' => $nameParts[1],
                'roles' => [
                    self::ROLE_SPECIALIST,
                ],
            ]);
        } else {
            /** @var RemoteUser $remoteUser */
            $remoteUser = $remoteUsers[0];
        }

        WisebeeUser::query()
            ->create([
                'wisebee_id' => $remoteUser->id,
                'admin_user_id' => $userID,
            ]);
    }
}
