<?php

namespace Tests\Unit\Services;

use App\Services\GraphService;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Tests\TestCase;
use Mockery;

class GraphServiceTest extends TestCase
{
    public function testReturnsSuccessfulResponseData()
    {
        Http::fake([
            '*' => Http::response(['visits' => 1234], 200),
        ]);

        $service = new GraphService();
        $response = $service->getGraph(['range' => '7d']);

        $this->assertEquals(['visits' => 1234], $response);
    }

    public function testCanLogErrorAndReturnErrorOnFailure()
    {
        Log::shouldReceive('warning')
            ->once()
            ->with('failed stats retrieval', Mockery::on(function ($context) {
                return isset($context['status']) && $context['status'] === 500;
            }));

        Http::fake([
            '*' => Http::response(['error' => 'Server down'], 500),
        ]);

        $service = new GraphService();
        $response = $service->getGraph();

        $this->assertEquals([
            '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>',
        ], $response);
    }

    public function testCanLogWarningAndReturnErrorOnException()
    {
        Log::shouldReceive('error')
            ->once()
            ->with('Connection timed out');

        Http::fake([
            '*' => Http::sequence()->push(fn() => throw new \Exception('Connection timed out')),
        ]);

        $service = new GraphService();
        $response = $service->getGraph();

        $this->assertEquals('fail', $response['status']);
    }
}
