<?php

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

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

    private $apiBaseUrl = 'https://bsky.social/xrpc/';

    private $HttpClient;

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

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

        $response = $this->login($id, $password);

        if ($response['status'] === 'error') {
            return (object) $response;
        }
        $loginResponse = $response['data'];
        $actor = $loginResponse->did;
        $accessToken = $loginResponse->accessJwt;

        $profile = $this->profileInfo($actor, $accessToken);

        return $this->accountInformation($profile, $loginResponse);
    }

    public function profileInfo($actor, $accessToken)
    {
        $url = $this->apiBaseUrl . 'app.bsky.actor.getProfile';
        $headers = [
            'Authorization' => 'Bearer ' . $accessToken,
            'Content-Type'  => 'application/json'
        ];

        $params = [
            'actor' => $actor
        ];

        $url .= '?' . http_build_query($params);

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

    public function login($id, $password)
    {
        $url = $this->apiBaseUrl . 'com.atproto.server.createSession';
        $body = [
            'identifier' => $id,
            'password'   => $password
        ];
        $headers = [
            'Content-Type' => 'application/json'
        ];
        $response = $this->HttpClient->request($url, 'POST', json_encode($body), $headers);

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

        return ['status' => 'success', 'data' => $response];
    }

    public function accountInformation($profile, $loginResponse)
    {
        $userId = $profile->did;
        $accountDetails = [
            'profile_id'    => $userId,
            'account_id'    => $userId,
            'account_name'  => empty($profile->displayName) ? $profile->handle : $profile->displayName,
            'account_type'  => 'profile',
            'platform'      => 'bluesky',
            'user_name'     => $profile->handle,
            'icon'          => $profile->avatar,
            'access_token'  => Hash::encrypt($loginResponse->accessJwt),
            'refresh_token' => Hash::encrypt($loginResponse->refreshJwt),
            'generateOn'    => time(),
        ];

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

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

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

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

        return $accountData;
    }
}
