<?php

namespace App\Classes\Modules\Accounts\Services;

use Illuminate\Support\Facades\Http;
use App\Classes\Exceptions\AccessUnauthorisedException;
use App\Classes\Modules\Accounts\DataTransferObjects\CrossAuthenticationCredentialsObject;
use App\Classes\ValueObjects\Constants\PlatformType;

class CrossAuthenticatesUser
{

    /**
     * @param CrossAuthenticationCredentialsObject $object
     * @return false|string
     * @throws AccessUnauthorisedException
     */

    public function execute(CrossAuthenticationCredentialsObject $object){

        if ($object->getPlatform() == PlatformType::EXCHANGE) {

            $token = $object->getAccessToken();

            $tokenParts = explode(".", $token);  
            $tokenPayload = base64_decode($tokenParts[1]);
            $jwtPayload = json_decode($tokenPayload);

            $response = Http::withToken($object->getAccessToken())->get(env('EXCHANGE_URL') . 'api/v1/company/' .  $jwtPayload->user->company_id . '/show')->object();

            $response_document = Http::withToken($object->getAccessToken())->get(env('EXCHANGE_URL') . 'api/v1/storage/' .  $response->payload->data->identification->files[0]->file->file_info[0]->original->file . '/fetch')->object();
            $response->token = $jwtPayload;
            $response->document = $response_document->payload;
        }

        return $response;

    }

}