<?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\Source\Provider\Instagram;

use function YOOtheme\app;
use YOOtheme\Event;
use ZOOlanders\YOOessentials\Auth\AuthManager;
use ZOOlanders\YOOessentials\Api\Instagram\InstagramBusinessApi;
use ZOOlanders\YOOessentials\Api\Instagram\InstagramPersonalApi;
use ZOOlanders\YOOessentials\Api\Instagram\InstagramApiInterface;

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

            if ($auth->driverName() === 'instagrambasic') {
                return app(InstagramPersonalApi::class)->forAccount($auth);
            }

            return app(InstagramBusinessApi::class)->forAccount($auth);
        } catch (\Exception $e) {
            Event::emit('yooessentials.error', [
                'addon' => 'source-instagram',
                'error' => $e->getMessage(),
                'exception' => $e,
            ]);

            return null;
        }
    }
}
