<?php

declare(strict_types=1);

/*
 * This file is part of the VitiCore 2.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Provider\SocialNetwork;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Client\ConnectCpCreationClient;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils\Mailer;
use CpCreation\VitiCore\SocialNetwork\Model\SocialNetwork;
use CpCreation\VitiCore\SocialNetwork\Repository\SocialNetworkRepository;
use Psr\Cache\CacheItemPoolInterface;

class FacebookFacebookProvider implements SocialNetworkProviderInterface
{
    public const TYPE = 'facebook_facebook';

    private string $accessToken = '';
    private string $userId = '';
    private ?SocialNetwork $social = null;

    public function __construct(
        private SocialNetworkRepository $socialNetworkRepository,
        private ConnectCpCreationClient $cpCreationClient,
        private CacheItemPoolInterface $cache,
        private Mailer $mailer,
    ) {
        /** @var SocialNetwork|null $social */
        $social = $this->socialNetworkRepository->findOneBy([
            'network' => self::TYPE,
        ]);

        $this->social = $social;
    }

    public function getMedias(int $count): array
    {
        if (null === $this->social) {
            return [];
        }

        $cacheItem = $this->cache->getItem('news.facebook_facebook');

        if ($cacheItem->isHit()) {
            $cached = $cacheItem->get();

            return \is_array($cached) ? $cached : [];
        }

        try {
            $this->loadCredentials();

            if ('' === $this->accessToken) {
                return [];
            }

            // À compléter avec le vrai appel API Facebook quand tu seras prêt.
            $medias = [];

            $cacheItem->expiresAfter(180);
            $cacheItem->set($medias);
            $this->cache->save($cacheItem);

            return $medias;
        } catch (\Throwable $e) {
            $this->mailer->sendErrorInstagram($e->getMessage());

            return [];
        }
    }

    public function getNetwork(): string
    {
        return self::TYPE;
    }

    private function loadCredentials(): void
    {
        if ('' !== $this->accessToken && '' !== $this->userId) {
            return;
        }

        if (null === $this->social) {
            return;
        }

        try {
            /** @var array{id?: string}|mixed $configuration */
            $configuration = $this->social->getConfiguration();

            $socialId = \is_array($configuration) ? ($configuration['id'] ?? null) : null;

            if (!\is_string($socialId) || '' === $socialId) {
                return;
            }

            $response = $this->cpCreationClient->get('api/client_socials/'.$socialId);

            /** @var array{token?: scalar|null, userId?: scalar|null} $result */
            $result = json_decode(
                $response->getBody()->getContents(),
                true,
                512,
                \JSON_THROW_ON_ERROR
            );

            $this->accessToken = isset($result['token']) ? (string) $result['token'] : '';
            $this->userId = isset($result['userId']) ? (string) $result['userId'] : '';
        } catch (\Throwable $e) {
            $this->mailer->sendErrorConnexionApiConnectSocialInstagram($e->getMessage());
        }
    }
}
