<?php

namespace Tests\Feature;

use App\Models\Mikrotik;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

class PackageMikrotikProfileTest extends TestCase
{
    use RefreshDatabase;

    public function test_connected_router_profiles_load_and_selected_pair_is_saved(): void
    {
        foreach (['package.view', 'package.create'] as $permission) {
            Permission::create(['name' => $permission]);
        }
        $role = Role::create(['name' => 'Admin']);
        $role->syncPermissions(['package.view', 'package.create']);
        $user = User::factory()->create();
        $user->assignRole($role);
        $router = Mikrotik::create([
            'name' => 'Core Router', 'ip_address' => 'core.ecomradeit.com', 'api_port' => 195,
            'username' => 'api', 'password' => 'secret', 'status' => true, 'connected' => true,
        ]);
        Cache::put('mikrotik:profiles:'.$router->id, [['name' => '20Mbps', 'rate' => '20M/20M']], now()->addHour());

        $this->actingAs($user)->getJson(route('admin.packages.mikrotik-profiles', ['mikrotik_id' => $router->id]))
            ->assertOk()->assertJsonPath('profiles.0.name', '20Mbps')->assertJsonPath('server.id', $router->id);

        $this->actingAs($user)->postJson(route('admin.packages.store'), [
            'name' => 'Home 20 Mbps', 'net_speed' => '20M/20M', 'price' => 800, 'status' => 1,
            'mikrotik_server_id' => $router->id, 'mikrotik_profile_name' => '20Mbps',
        ])->assertCreated();

        $this->assertDatabaseHas('packages', [
            'name' => 'Home 20 Mbps', 'price' => 800, 'mikrotik_server_id' => $router->id, 'mikrotik_profile_name' => '20Mbps',
        ]);
    }

    public function test_unknown_profile_cannot_be_attached_to_router(): void
    {
        Permission::create(['name' => 'package.create']);
        $role = Role::create(['name' => 'Admin']);
        $role->givePermissionTo('package.create');
        $user = User::factory()->create();
        $user->assignRole($role);
        $router = Mikrotik::create([
            'name' => 'Core Router', 'ip_address' => '192.0.2.10', 'api_port' => 195,
            'username' => 'api', 'password' => 'secret', 'status' => true, 'connected' => true,
        ]);
        Cache::put('mikrotik:profiles:'.$router->id, [['name' => '10Mbps']], now()->addHour());

        $this->actingAs($user)->postJson(route('admin.packages.store'), [
            'name' => 'Tampered', 'price' => 500, 'status' => 1,
            'mikrotik_server_id' => $router->id, 'mikrotik_profile_name' => 'OtherRouterProfile',
        ])->assertUnprocessable()->assertJsonValidationErrors('mikrotik_profile_name');
    }
}
