<?php

namespace Tests\Feature;

use App\Models\Vendor;
use App\Services\Providers\SmeplugProvider;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class SmeplugProviderDocsAlignmentTest extends TestCase
{
    use RefreshDatabase;

    public function test_balance_read_accepts_boolean_success_flag(): void
    {
        Http::fake([
            'https://smeplug.ng/api/v1/account/balance' => Http::response([
                'status' => true,
                'balance' => 15000,
            ], 200),
        ]);

        $provider = new SmeplugProvider($this->makeVendor());
        $result = $provider->getBalance();

        $this->assertTrue($result['success']);
        $this->assertSame(15000, data_get($result, 'body.balance'));
    }

    public function test_query_transaction_uses_data_current_status_for_pending(): void
    {
        Http::fake([
            'https://smeplug.ng/api/v1/transactions/REF-123' => Http::response([
                'status' => true,
                'data' => [
                    'current_status' => 'pending',
                    'reference' => 'SP-REF-001',
                    'price' => '480',
                ],
                'message' => 'Queued',
            ], 200),
        ]);

        $provider = new SmeplugProvider($this->makeVendor());
        $response = $provider->queryTransaction(['reference' => 'REF-123']);

        $this->assertTrue($response->isPending());
        $this->assertSame('SP-REF-001', $response->vendorReference);
        $this->assertSame(480.0, $response->vendorCost);
    }

    public function test_query_transaction_uses_data_current_status_for_success(): void
    {
        Http::fake([
            'https://smeplug.ng/api/v1/transactions/REF-124' => Http::response([
                'status' => true,
                'data' => [
                    'current_status' => 'delivered',
                    'reference' => 'SP-REF-002',
                    'price' => '510',
                ],
                'message' => 'Delivered',
            ], 200),
        ]);

        $provider = new SmeplugProvider($this->makeVendor());
        $response = $provider->queryTransaction(['reference' => 'REF-124']);

        $this->assertTrue($response->isSuccess());
        $this->assertSame('SP-REF-002', $response->vendorReference);
        $this->assertSame(510.0, $response->vendorCost);
    }

    protected function makeVendor(): Vendor
    {
        $vendor = new Vendor([
            'name' => 'SMEPlug Test',
            'type' => 'smeplug',
            'base_url' => 'https://smeplug.ng',
            'auth_type' => 'bearer',
            'status' => 'active',
            'timeout_seconds' => 30,
            'webhook_enabled' => true,
        ]);
        $vendor->secret = 'test-private-key';
        $vendor->save();

        return $vendor->refresh();
    }
}

