<?php

declare(strict_types=1);

use App\Services\External\DadataBalanceProvider;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

uses(TestCase::class); // нужен booted-app: config()/app()/Http::fake()

it('читает баланс DaData по API c X-Secret', function () {
    config()->set('services.dadata.api_key', 'test-token');
    config()->set('services.dadata.secret', 'test-secret');
    Http::fake(['dadata.ru/*' => Http::response(['balance' => 4500.0], 200)]);
    $r = app(DadataBalanceProvider::class)->fetch();
    expect($r->ok)->toBeTrue();
    expect($r->balance)->toBe(4500.0);
    expect($r->serviceKey)->toBe('dadata');
    Http::assertSent(fn ($req) => $req->hasHeader('Authorization', 'Token test-token')
        && $req->hasHeader('X-Secret', 'test-secret'));
});

it('ошибка API → fail, не бросает', function () {
    config()->set('services.dadata.api_key', 'test-token');
    Http::fake(['dadata.ru/*' => Http::response('forbidden', 403)]);
    $r = app(DadataBalanceProvider::class)->fetch();
    expect($r->ok)->toBeFalse();
    expect($r->error)->not->toBeNull();
});

it('нет ключа → fail без сетевого вызова', function () {
    config()->set('services.dadata.api_key', '');
    Http::fake();
    $r = app(DadataBalanceProvider::class)->fetch();
    expect($r->ok)->toBeFalse();
    Http::assertNothingSent();
});
