<?php

namespace Tests\Feature;

use App\Models\Category;
use App\Models\Network;
use App\Models\Plan;
use App\Models\Transaction;
use App\Models\User;
use App\Models\Wallet;
use App\Models\WalletLedger;
use App\Services\TransactionService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;

class NoVendorRoutePreventsDebitTest extends TestCase
{
    use RefreshDatabase;

    public function test_purchase_fails_before_debit_when_no_active_vendor_route_exists(): void
    {
        $user = User::factory()->create();
        Wallet::create(['user_id' => $user->id, 'balance' => 1000]);

        $category = Category::create([
            'name' => 'Data Direct',
            'slug' => 'data_direct',
        ]);

        $network = Network::create([
            'name' => 'MTN',
            'slug' => 'mtn',
            'vendor_network_code_json' => ['msorg' => ['data' => '1']],
        ]);

        $plan = Plan::create([
            'network_id' => $network->id,
            'category_id' => $category->id,
            'name' => 'MTN DIRECT 500MB',
            'value' => '500MB',
            'selling_price' => 400,
            'status' => 'available',
            'sort_order' => 1,
        ]);

        /** @var TransactionService $service */
        $service = $this->app->make(TransactionService::class);

        try {
            $service->purchase($user, [
                'category_slug' => 'data_direct',
                'plan_id' => $plan->id,
                'phone' => '08030000000',
                'mobile_number' => '08030000000',
                'internal_reference' => 'NO-ROUTE-001',
            ]);
            $this->fail('Expected ValidationException was not thrown.');
        } catch (ValidationException $e) {
            $this->assertArrayHasKey('service', $e->errors());
        }

        $this->assertSame('1000.00', (string) $user->fresh()->wallet->balance);
        $this->assertSame(0, Transaction::query()->count());
        $this->assertSame(0, WalletLedger::query()->count());
    }
}

