<?php

namespace BitApps\SocialPro\HTTP\Services\Social\TelegramService;

use BitApps\Social\HTTP\Services\Traits\LoggerTrait;
use BitApps\Social\Model\Account;
use BitApps\Social\Utils\Common;
use BitApps\Social\Utils\Hash;
use BitApps\SocialPro\Deps\BitApps\WPKit\Http\Client\HttpClient;

class TelegramTokenService
{
    use Common, LoggerTrait;

    private $apiBaseUrl = 'https://api.telegram.org/bot';

    private $HttpClient;

    public function __construct()
    {
        $this->HttpClient = new HttpClient();
    }

    public function authHandler($request)
    {
        $body = $request->body();
        $payload = $body['payload'] ?? [];

        $token = $payload['token'] ?? null;

        $tokenInfo = $this->getMe($token);

        if (!$tokenInfo->ok) {
            return (object) [
                'status'  => 'error',
                'message' => $tokenInfo->description ?? 'Invalid token or unable to fetch user information.',
            ];
        }

        $chatList = $this->getChatList($token);

        if (empty($chatList)) {
            return (object) [
                'status'  => 'error',
                'message' => 'No chats found or token is invalid.',
            ];
        }

        return $this->formatChatAccounts($chatList, $token);
    }

    public function getMe($token)
    {
        $url = "{$this->apiBaseUrl}{$token}/getMe";

        return $this->HttpClient->request($url, 'POST', []);
    }

    public function getChatList($token)
    {
        $url = "{$this->apiBaseUrl}{$token}/getUpdates";

        $updates = $this->HttpClient->request($url, 'POST', []);

        $list = [];
        $uniqChats = [];

        foreach ($updates->result as $update) {
            if (!isset($update->message) && !isset($update->channel_post)) {
                continue;
            }

            $chat = $update->message->chat ?? ($update->channel_post->chat ?? null);

            if (!$chat || empty($chat->id)) {
                continue;
            }

            $chatId = $chat->id;

            if (isset($uniqChats[$chatId])) {
                continue;
            }

            $uniqChats[$chatId] = true;

            $name = $chat->first_name ?? $chat->title ?? '[no name]';

            $list[] = [
                'id'       => $chatId,
                'name'     => $name,
                'username' => $chat->username ?? '',
            ];
        }

        return $list;
    }

    public function formatChatAccounts($chatList, $token)
    {
        $accountData = [];

        foreach ($chatList as $chat) {
            $id = $chat['id'];
            $name = $chat['name'];
            $type = 'chat';
            $icon = '';
            $accountData[] = $this->accountInformation($id, $name, $type, $icon, $token);
        }

        return $accountData;
    }

    public function accountInformation($id, $name, $type, $icon, $token)
    {
        $accountDetails = [
            'profile_id'   => $id,
            'account_id'   => $id,
            'account_name' => empty($name) ? $id : $name,
            'account_type' => $type,
            'platform'     => 'telegram',
            'user_name'    => $name,
            'icon'         => $icon ?? '',
            'access_token' => Hash::encrypt($token),
            'generateOn'   => time(),
        ];

        $userData['profile_id'] = $id;
        $userData['account_id'] = $id;
        $userData['account_name'] = $accountDetails['account_name'];
        $userData['details'] = json_encode($accountDetails);
        $userData['platform'] = 'telegram';
        $userData['account_type'] = Account::accountType['CUSTOM'];
        $userData['status'] = Account::ACCOUNT_STATUS['active'];

        $totalAccount = Account::where('account_id', $id)->count();
        $isConnected = true;

        if (!$totalAccount || $totalAccount === 0) {
            $isConnected = false;
        }

        return ['account' => $userData, 'isConnected' => $isConnected];
    }
}
