<?php

namespace Tests\Feature;

use App\Models\Asns;
use App\Models\Goliath\GoliathHistory;
use App\Models\Organisation;
use App\Models\Prefixes;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class GoliathFilterRenameMigrationTest extends TestCase
{
    use RefreshDatabase;

    /**
     *  DESCRIPTION: The migration renames fivem_tcp_gated to fivem_double_handshake
     *  in place, leaves every other filter and every other row alone, and writes
     *  no flag history while doing so.
     */
    public function testRenamesTheGatedFilterOnly(): void
    {
        $organisation = Organisation::create(['id' => 1, 'name' => 'A']);
        $asn = Asns::create(['asn' => 64512, 'organisation_id' => $organisation->id, 'approved' => 1]);

        $gated = Prefixes::factory()->ownership($organisation, $asn)->flags(filters: ['fivem' => ['30110'], 'fivem_tcp_gated' => ['30120'], 'wireguard' => ['51820']])->create();
        $plain = Prefixes::factory()->ownership($organisation, $asn)->flags(filters: ['fivem' => ['30110']])->create();
        $none = Prefixes::factory()->ownership($organisation, $asn)->flags()->create();

        $history = GoliathHistory::count();

        (require database_path('migrations/2026_10_12_000001_goliath_double_handshake_filter_rename.php'))->up();

        $filters = fn (Prefixes $prefix) => json_decode(DB::table('prefix_goliath_flags')->where('prefix_id', '=', $prefix->id)->value('flag_filters'), true);

        $this->assertSame(['fivem' => ['30110'], 'fivem_double_handshake' => ['30120'], 'wireguard' => ['51820']], $filters($gated), 'The gated filter should be renamed in place and its neighbours left alone.');
        $this->assertSame(['fivem' => ['30110']], $filters($plain), 'A row without the gated filter should be left alone.');
        $this->assertNull($filters($none), 'A row without filters should be left alone.');
        $this->assertSame($history, GoliathHistory::count(), 'The rename should write no flag history.');
    }
}
