<?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\Form\Action\Mailchimp;

use function YOOtheme\app;
use YOOtheme\Event;
use ZOOlanders\YOOessentials\Api\Mailchimp\MailchimpApi;
use ZOOlanders\YOOessentials\Auth\AuthManager;

trait HasApiRequest
{
    public static function api(string $authId): MailchimpApi
    {
        try {
            $auth = app(AuthManager::class)->auth($authId);

            if ($auth->driver()->type() === 'oauth') {
                return app(MailchimpApi::class)->withAccessToken($auth->accessToken(), $auth->dc);
            }

            return app(MailchimpApi::class)->withApiKey($auth->key);
        } catch (\Exception $e) {
            Event::emit('yooessentials.error', [
                'addon' => 'form-action',
                'provider' => 'mailchimp',
                'error' => $e->getMessage(),
                'exception' => $e
            ]);

            return app(MailchimpApi::class);
        }
    }
}
