<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Auth\Listener;

use YOOtheme\Arr;
use YOOtheme\Event;
use ZOOlanders\YOOessentials\Auth\Auth;
use ZOOlanders\YOOessentials\Auth\AuthManager;

class SaveAuths
{
    public AuthManager $manager;

    public function __construct(AuthManager $manager)
    {
        $this->manager = $manager;
    }

    public function handle($values): array
    {
        $key = AuthManager::AUTHS_CONFIG_KEY;

        try {
            $auths = $this->manager->createAuths(Arr::get($values, $key, []));
            $auths = AuthManager::removeDuplicates($auths);

            $auths = array_map(function (Auth $auth) {
                return $auth->withEncryptedKeys()->toArray();
            }, $auths);

            Arr::set($values, $key, $auths);

            return $values;
        } catch (\Exception $e) {
            Event::emit('yooessentials.error', [
                'addon' => 'auth',
                'task' => 'save-config',
                'error' => $e->getMessage(),
            ]);

            return $values;
        }
    }
}
