<?php

namespace Mtc\Plugins\Wisebee\Classes\Handlers;

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

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

    const ROLE_SPECIALIST = 'specialist';

    public function handleAdminCreated(int $userID): void
    {
        if (empty($userID)) {
            return;
        }

        /** @var AdminUser|null $adminUser */
        $adminUser = AdminUser::query()
            ->find($userID);

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

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

            if (!empty($remoteUsers)) {
                /** @var RemoteUser $remoteUser */
                $remoteUser = $remoteUsers[0];
            } else {
                $nameParts = explode(' ', trim((string)$adminUser->name), 2);
                $firstname = $nameParts[0] ?? '';
                $lastname = $nameParts[1] ?? '';

                $remoteUser = $this->wisebee->create(RemoteUser::class, [
                    'email' => $adminUser->email,
                    'firstname' => $firstname,
                    'lastname' => $lastname,
                    'roles' => [
                        self::ROLE_SPECIALIST,
                    ],
                ]);

                if (empty($remoteUser) || empty($remoteUser->id)) {
                    error_log('Wisebee UserHandler: failed to create remote user for admin ' . $userID . ': ' . $this->wisebee->getErrorMessage());
                    return;
                }
            }
        } catch (Throwable $e) {
            error_log('Wisebee UserHandler: exception syncing admin ' . $userID . ': ' . $e->getMessage());
            return;
        }

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