<?php

namespace RebelCode\Spotlight\Instagram\Pro\Engine\Providers;

use GuzzleHttp\ClientInterface;
use RebelCode\Iris\Fetching\ItemProvider;
use RebelCode\Iris\Result;
use RebelCode\Iris\Source;
use RebelCode\Spotlight\Instagram\Engine\Providers\IgProvider;
use RebelCode\Spotlight\Instagram\Engine\Sources\TaggedUserSource;
use RebelCode\Spotlight\Instagram\IgApi\IgApiUtils;
use RebelCode\Spotlight\Instagram\PostTypes\AccountPostType;
use RebelCode\Spotlight\Instagram\Wp\PostType;

/**
 * Provides Instagram media where an Instagram account is tagged.
 *
 * @since 0.5
 */
class IgTaggedMediaProvider implements ItemProvider
{
    const DEFAULT_LIMIT = 50;

    /**
     * The HTTP client.
     *
     * @since 0.5
     *
     * @var ClientInterface
     */
    protected $client;

    /**
     * The accounts post type.
     *
     * @since 0.5
     *
     * @var PostType
     */
    protected $accounts;

    /**
     * Constructor.
     *
     * @since 0.5
     *
     * @param ClientInterface $client The HTTP client.
     * @param PostType        $accounts The accounts post type.
     */
    public function __construct(ClientInterface $client, PostType $accounts)
    {
        $this->client = $client;
        $this->accounts = $accounts;
    }

    /**
     * @inheritDoc
     *
     * @since 0.5
     */
    public function getItems(Source $source, ?int $limit = null, int $offset = 0) : Result
    {
        $username = $source->data['name'] ?? null;

        if ($source->type !== TaggedUserSource::TYPE || empty($username)) {
            return Result::empty();
        }

        $account = AccountPostType::getByUsername($this->accounts, $username);
        if ($account === null) {
            return Result::error("Account \"{$username}\" does not exist on this site");
        }

        $userId = $account->user->id;
        $accessToken = $account->accessToken;

        $limit = $limit ?? static::DEFAULT_LIMIT;
        $baseUrl = IgProvider::GRAPH_API_URL;

        return IgProvider::request($this->client, $source, "{$baseUrl}/{$userId}/tags", [
            'limit' => $limit,
            'offset' => $offset,
            'access_token' => $accessToken->code,
            'fields' => implode(',', IgApiUtils::getBusinessMediaFields(false)),
        ]);
    }
}
