<?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\Type;

use ZOOlanders\YOOessentials\Source\GraphQL\AbstractQueryType;
use ZOOlanders\YOOessentials\Source\GraphQL\HasSourceInterface;
use ZOOlanders\YOOessentials\Source\Resolver\CachesResolvedSourceData;
use ZOOlanders\YOOessentials\Source\Resolver\LoadsSourceFromArgs;
use ZOOlanders\YOOessentials\Source\Provider\Instagram\HasApiRequest;
use ZOOlanders\YOOessentials\Source\Provider\Instagram\InstagramBusinessSource;

class InstagramBusinessUserQueryType extends AbstractQueryType implements HasSourceInterface
{
    use LoadsSourceFromArgs, CachesResolvedSourceData, HasApiRequest;

    public function name(): string
    {
        $id = $this->source()->id();

        return "instagramUser_{$id}_query";
    }

    public function label(): string
    {
        return "{$this->source()->name()} User";
    }

    public static function getCacheKey(): string
    {
        return 'instagram-user';
    }

    public function config(): array
    {
        return [
            'fields' => [
                $this->name() => [
                    'type' => InstagramBusinessUserType::TYPE_NAME,

                    'args' => [
                        'cache' => [
                            'type' => 'Int',
                        ],
                    ],

                    'metadata' => [
                        'group' => 'Instagram',
                        'label' => $this->label(),
                        'fields' => [
                            'cache' => $this->cacheField(),
                        ],
                    ],

                    'extensions' => [
                        'call' => [
                            'func' => __CLASS__ . '::resolve',
                            'args' => [
                                'source_id' => $this->source->id(),
                            ],
                        ],
                    ],
                ],
            ],
        ];
    }

    public static function resolve($root, array $args): array
    {
        /** @var InstagramBusinessSource */
        $source = self::loadSource($args, InstagramBusinessSource::class);

        if (!$source) {
            return [];
        }

        return self::resolveFromCache($source, $args, function () use ($source) {
            return self::api($source->account())->user($source->pageId());
        });
    }
}
