<?php

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

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 LineTokenService
{
    use Common, LoggerTrait;

    private $apiBaseUrl = 'https://api.line.me/v2/bot/';

    private $HttpClient;

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

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

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

        if (!$type || !$id || !$token) {
            return (object) [
                'status'  => 'error',
                'message' => 'Invalid payload. Required fields: type, id, token.'
            ];
        }

        switch ($type) {
            case 'group':
                return $this->getGroupInfo($id, $token);

            case 'user':
                return $this->getUserInfo($id, $token);

            default:
                return (object) [
                    'status'  => 'error',
                    'message' => 'Invalid type. Expected "group" or "user".'
                ];
        }
    }

    public function getGroupInfo($id, $token)
    {
        $url = "{$this->apiBaseUrl}group/{$id}/summary";

        $headers = [
            'Authorization' => 'Bearer ' . $token,
        ];

        $response = $this->HttpClient->request($url, 'GET', [], $headers);

        if (!isset($response->groupId) && isset($response->message)) {
            return (object) [
                'status'  => 'error',
                'message' => $response->message,
            ];
        }

        return $this->accountInformation($response->groupId, $response->groupName, 'group', $response->pictureUrl, $token);
    }

    public function getUserInfo($id, $token)
    {
        $url = "{$this->apiBaseUrl}profile/{$id}";

        $headers = [
            'Authorization' => 'Bearer ' . $token,
        ];

        $response = $this->HttpClient->request($url, 'GET', [], $headers);

        if (!isset($response->userId) && isset($response->message)) {
            return (object) [
                'status'  => 'error',
                'message' => $response->message,
            ];
        }

        return $this->accountInformation($response->userId, $response->displayName, 'profile', $response->pictureUrl, $token);
    }

    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'     => 'line',
            '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'] = 'line';
        $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;
        }

        $accountData[] = ['account' => $userData, 'isConnected' => $isConnected];

        return $accountData;
    }
}
