<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class GraphService
{
    public function getGraph(array $data = []): array
    {
        try {
            $result = Http::connectTimeout(1)
                ->withHeaders([
                    'x-tenant' => tenant('id'),
                ])
                ->withOptions(['verify' => false])
                ->post($this->endpoint('graph'), $data);

            if ($result->successful()) {
                return $result->json();
            }
            Log::warning('failed stats retrieval', [
                'url' => $this->endpoint('graph'),
                'status' => $result->status(),
                'result' => $result->json(),
            ]);
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
        }
        return $this->graphError();
    }

    private function graphError(): array
    {
        return [
            'status' => 'fail',
            'message' => 'Could not load stats for site visitors. Please ensure '
                . '<a href="/settings/site/seo">GA account is set up and access is granted</a>',
        ];
    }

    private function endpoint(string $string)
    {
        return rtrim(config('services.graph.domain'), '/') . '/' . $string;
    }
}
