<?php

namespace FSPoster\App\SocialNetworks\YoutubeShorts\Adapters;

use FSPoster\App\Models\Channel;
use FSPoster\App\Providers\Channels\ChannelService;
use FSPoster\App\Providers\License\PlanFeatures;
use FSPoster\App\SocialNetworks\YoutubeShorts\Api\Api;
use FSPoster\App\SocialNetworks\YoutubeShorts\App\Bootstrap;

class ChannelAdapter
{
    public static function fetchChannels( Api $api ): array
    {
        $channelInfo = $api->getMyInfo();

        $channelId   = $channelInfo['id'] ?? '-';
        $channelName = $channelInfo['snippet']['title'] ?? '-';
        $avatar      = $channelInfo['snippet']['thumbnails']['default']['url'] ?? '';

        $channelSessionId = ChannelService::addChannelSession( [
            'name'           => $channelName,
            'social_network' => Bootstrap::getInstance()->getSlug(),
            'remote_id'      => $channelId,
            'proxy'          => $api->proxy,
            'method'         => 'app',
            'data'           => [
                'auth_data' => (array)$api->authData,
            ],
        ] );

        $existingChannels = Channel::where( 'channel_session_id', $channelSessionId )
                                   ->select( [ 'id', 'remote_id' ], true )
                                   ->fetchAll();

        $existingChannelsIdToRemoteIdMap = [];

        foreach ( $existingChannels as $existingChannel )
        {
            $existingChannelsIdToRemoteIdMap[ $existingChannel->remote_id ] = $existingChannel->id;
        }

        $channelsList   = [];
        $channelsList[] = [
            'id'                 => $existingChannelsIdToRemoteIdMap[ $channelId ] ?? null,
            'name'               => $channelName,
            'social_network'     => Bootstrap::getInstance()->getSlug(),
            'channel_type'       => 'account',
            'remote_id'          => $channelId,
            'channel_session_id' => $channelSessionId,
            'picture'            => $avatar,
        ];

        return $channelsList;
    }

    public static function refreshAndUpdateChannelSessionIfNeeded( int $channelSessionId, Api $api ): void
    {
        if (!empty($api->authData->accessTokenExpiresOn) && (time() + 30) < $api->authData->accessTokenExpiresOn) {
            return;
        }

        $api->refreshAccessToken();

        ChannelService::updateChannelSessionData($channelSessionId, [
            'auth_data' => (array)$api->authData,
        ]);
    }
}
