<?php

namespace App\Support;

use Exception;
use Illuminate\Support\Facades\Log;
use SevenShores\Hubspot\Factory;
use Throwable;

class HubSpotClient
{
    protected $api;

    public function __construct()
    {
        $accessToken = config('services.hubspot.access_token');
        if ($accessToken) {
            $this->api = Factory::createWithAccessToken($accessToken);
        } else {
            throw new Exception('HubsSpot Client - Unable to initiate API: no access token set');
        }
    }

    public function getContactById(int $id)
    {
        try {
            $contact = $this->api->contacts()->getById($id);
        } catch(Throwable $e) {
            Log::warning('Unable to get contact no ' . $id . ' from HubSpot. Possibly doesnt exist');
            return null;
        }

        if (empty($contact->properties->contact_number)) {
            Log::warning('Unable to get contact no ' . $id . ' from HubSpot. No contact number');
            return null;
        }

        return [
            'hubspotId' => $id,
            'email' => $contact->properties->email,
            'navNo' => $contact->properties->contact_number->value
        ];
    }
}
