<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class WalletBalanceTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->withoutMiddleware(EnsurePlatformSession::class);
        config([
            'billing.api_url' => 'https://billing.test',
            'billing.api_key' => 'test-care-key',
            'billing.currency' => 'GHS',
        ]);
    }

    public function test_wallet_balance_endpoint_returns_formatted_json(): void
    {
        Http::fake([
            'billing.test/balance*' => Http::response(['balance_minor' => 12550]),
        ]);

        $user = User::create([
            'public_id' => 'care-wallet-user',
            'name' => 'Wallet User',
            'email' => 'wallet@example.com',
        ]);

        $this->actingAs($user)
            ->getJson(route('wallet.balance'))
            ->assertOk()
            ->assertJson([
                'available' => true,
                'balance_minor' => 12550,
                'currency' => 'GHS',
                'formatted' => 'GHS 125.50',
            ]);

        Http::assertSent(function ($request) {
            return str_contains($request->url(), '/balance')
                && $request['user'] === 'care-wallet-user';
        });
    }

    public function test_wallet_balance_endpoint_marks_unavailable_when_billing_fails(): void
    {
        Http::fake([
            'billing.test/balance*' => Http::response(['error' => 'unauthorized'], 401),
        ]);

        $user = User::create([
            'public_id' => 'care-wallet-user-2',
            'name' => 'Wallet User',
            'email' => 'wallet2@example.com',
        ]);

        $this->actingAs($user)
            ->getJson(route('wallet.balance'))
            ->assertOk()
            ->assertJson(['available' => false]);
    }

    public function test_wallet_balance_route_is_not_the_account_redirect(): void
    {
        $this->assertSame('wallet.balance', config('billing.wallet_balance_route'));
        $this->assertTrue(\Illuminate\Support\Facades\Route::has('wallet.balance'));
        $this->assertNotSame(route('care.wallet'), route('wallet.balance'));
    }
}
