<?php

namespace PublishPress\FuturePro\Modules\Workflows\Domain\Engine\InputValidators;

use PublishPress\Future\Modules\Workflows\Interfaces\InputValidatorsInterface;
use PublishPress\Future\Modules\Workflows\Module;

class UserQuery implements InputValidatorsInterface
{
    public function validate(array $args): bool
    {
        $userId = $args['userId'];
        $roles = $args['roles'];
        $node = $args['node'];
        $nodeSettings = $node['data']['settings'] ?? [];

        $user = get_user_by('id', $userId);

        if (! $this->hasValidUserId($user, $nodeSettings)) {
            return false;
        }

        if (! $this->hasValidUserRoles($roles, $nodeSettings)) {
            return false;
        }


        return true;
    }

    private function hasValidUserId($user, array $nodeSettings)
    {
        if (! $user) {
            return false;
        }

        $settingUserIds = $nodeSettings['userQuery']['userId'] ?? [];

        if (empty($settingUserIds)) {
            return true;
        }

        return in_array($user->ID, $settingUserIds);
    }

    private function hasValidUserRoles($roles, array $nodeSettings)
    {
        $settingUserRoles = $nodeSettings['userQuery']['userRole'] ?? [];

        if (empty($settingUserRoles)) {
            return true;
        }

        if (empty($roles)) {
            return false;
        }

        $roles = array_map('trim', $roles);
        $settingUserRoles = array_map('trim', $settingUserRoles);

        $intersectingRoles = array_intersect($roles, $settingUserRoles);

        return ! empty($intersectingRoles);
    }
}
