<?php

namespace Tests\Feature;

use App\Models\Olt;
use App\Models\Setting;
use App\Services\OltGatewayService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class OltGatewayServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_registers_olt_using_server_side_encrypted_api_key(): void
    {
        Cache::flush();
        Setting::create(['key' => 'olt_gateway.url', 'value' => 'https://olt-gateway.test', 'type' => 'string']);
        Setting::create(['key' => 'olt_gateway.api_key', 'value' => Crypt::encryptString('prefix.private-key'), 'type' => 'string']);
        $olt = Olt::create([
            'name' => 'Main OLT', 'brand' => 'bdcom', 'model' => 'P3608', 'protocol' => 'snmp',
            'ip_address' => '10.10.20.2', 'snmp_port' => 161, 'community' => 'private-community', 'status' => true,
        ]);
        Http::fake([
            'https://olt-gateway.test/api/v1/olts' => Http::response(['data' => ['uuid' => '9da2efc3-1613-4fd4-8a9e-08f1b7b7a001', 'status' => 'pending']], 201),
        ]);

        app(OltGatewayService::class)->registerOrUpdate($olt);

        $this->assertSame('9da2efc3-1613-4fd4-8a9e-08f1b7b7a001', $olt->fresh()->gateway_uuid);
        Http::assertSent(fn (Request $request) => $request->hasHeader('X-OLT-API-KEY', 'prefix.private-key')
            && $request['vendor'] === 'bdcom'
            && $request['host'] === '10.10.20.2'
            && $request['community'] === 'private-community');
    }
}
