<?php

namespace App\Services;

use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\Tenant;

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();
    }

    public function visitorCount(Tenant $tenant, Carbon $date): int
    {

        try {
            $response = Http::timeout(10)
                ->withHeaders([
                    'X-Tenant' => $tenant->id,
                ])
                ->withOptions(['verify' => false])
                ->get($this->endpoint("visitors"), [
                    'date' => $date->format('Y-m-d'),
                ]);

            if ($response->successful()) {
                return (int) ($response->json('visitors') ?? 0);
            }
        } catch (\Exception $e) {
            Log::warning("Failed to fetch visitor count for tenant $tenant->id: {$e->getMessage()}");
        }

        return 0;
    }

    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((string) config('services.graph.domain'), '/') . '/' . $string;
    }
}
