<?php

namespace PublishPress\FuturePro\Modules\Workflows\Models;

use PublishPress\FuturePro\Modules\Workflows\Interfaces\RecipientsModelInterface;

class RecipientsModel implements RecipientsModelInterface
{
    public function __construct()
    {
    }

    public function resolveRecipients(array $recipients): array
    {
        $resolvedRecipients = [];

        foreach ($recipients as $recipient) {
            $resolvedRecipients = array_merge($resolvedRecipients, $this->resolveRecipientToUserId($recipient));
        }

        $resolvedRecipients = array_unique($resolvedRecipients);

        return $resolvedRecipients;
    }

    /**
     * Recepients can be a list of user names, IDs, and user roles.
     */
    public function resolveRecipientToUserId(string $recipient): array
    {
        if (is_numeric($recipient)) {
            $user = get_user_by('id', $recipient);
        } else {
            $user = get_user_by('login', $recipient);

            if (! $user) {
                $user = get_user_by('email', $recipient);
            }
        }

        if ($user) {
            return [$user->ID];
        }

        $usersByRole = get_users([
            'role' => $recipient,
        ]);

        if ($usersByRole) {
            return array_map(function ($user) {
                return $user->ID;
            }, $usersByRole);
        }

        return [];
    }
}
