<?php

namespace Tests\Tenant\Services;

use App\Services\AutoTraderApi;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Tests\TenantTestCase;

class AutoTraderApiTest extends TenantTestCase
{
    private string $prefix = 'https://api-sandbox.autotrader.co.uk';
    private string $liveUrl = 'https://api.autotrader.co.uk/';

    private AutoTraderApi $api;

    #[\Override]
    protected function setUp(): void
    {
        parent::setUp();

        Cache::shouldReceive('remember')->andReturn('fake-access-token');
        Log::spy();

        $this->api = new AutoTraderApi([
            'api_key' => 'key',
            'api_secret' => 'secret',
            'use_live_api' => false,
        ]);
    }

    public function testPostRequestWithoutQueryParams()
    {
        Http::fake([
            $this->prefix . '/test-endpoint' => Http::response(['data' => 'value']),
        ]);

        $response = $this->api->post('test-endpoint');

        $this->assertEquals('value', $response['data']);

        Http::assertSent(fn ($request) => $request->url() === $this->prefix . '/test-endpoint' &&
            $request->method() === 'POST' &&
            $request->hasHeader('Authorization', 'Bearer fake-access-token'));
    }

    public function testPostRequestWithQueryParams()
    {
        Http::fake([
            $this->prefix . '/test-endpoint*' => Http::response(['status' => 'hello'], 200),
        ]);

        $response = $this->api->post('test-endpoint', [], ['query' => ['page' => 2]]);

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

        Http::assertSent(fn ($request) => str_contains((string) $request->url(), 'page=2'));
    }

    public function testPostRequestLogsErrorOnFailure()
    {
        Http::fake([
            $this->prefix . '/fail' => Http::response(['error' => 'Something went wrong'], 500),
        ]);

        $this->api->post('fail');

        Log::shouldHaveReceived('error')->once();
    }

    public function testEndpointCanReturnLiveUrl()
    {
        $api = new AutoTraderApi([
            'api_key' => 'test-key',
            'api_secret' => 'test-secret',
            'use_live_api' => true,
        ]);

        $path = 'test-endpoint';
        $url = $api->endpoint($path);

        $this->assertEquals($this->liveUrl . $path, $url);
    }
}
