<?php

namespace Tests\Feature;

use App\Models\Server;
use App\Models\ServerGroup;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ServerGroupModelTest extends TestCase
{
    use RefreshDatabase;

    public function test_a_group_gets_a_uuid_route_key(): void
    {
        $g = ServerGroup::create(['name' => 'Produktion', 'color' => 'accent']);

        $this->assertNotEmpty($g->uuid);
        $this->assertSame('uuid', $g->getRouteKeyName());
    }

    public function test_color_falls_back_to_accent_for_an_unknown_token(): void
    {
        // R3: the colour must always be a real @theme token key — never arbitrary/raw text.
        $g = ServerGroup::create(['name' => 'x', 'color' => 'rebeccapurple']);

        $this->assertSame('accent', $g->fresh()->color);
    }

    public function test_a_known_color_token_is_kept(): void
    {
        $g = ServerGroup::create(['name' => 'y', 'color' => 'cyan']);

        $this->assertSame('cyan', $g->fresh()->color);
    }

    public function test_servers_belong_to_groups_both_ways(): void
    {
        $prod = ServerGroup::create(['name' => 'prod', 'color' => 'online']);
        $a = Server::create(['name' => 'a', 'ip' => '10.0.0.1', 'ssh_port' => 22, 'status' => 'online']);
        $b = Server::create(['name' => 'b', 'ip' => '10.0.0.2', 'ssh_port' => 22, 'status' => 'online']);

        $prod->servers()->attach([$a->id, $b->id]);

        $this->assertEqualsCanonicalizing([$a->id, $b->id], $prod->servers->pluck('id')->all());
        $this->assertTrue($a->groups->contains($prod));
    }

    public function test_in_group_scope_filters_to_members(): void
    {
        $prod = ServerGroup::create(['name' => 'prod', 'color' => 'online']);
        $member = Server::create(['name' => 'm', 'ip' => '10.0.0.1', 'ssh_port' => 22, 'status' => 'online']);
        $outsider = Server::create(['name' => 'o', 'ip' => '10.0.0.2', 'ssh_port' => 22, 'status' => 'online']);
        $prod->servers()->attach($member->id);

        $ids = Server::inGroup($prod->id)->pluck('id');

        $this->assertTrue($ids->contains($member->id));
        $this->assertFalse($ids->contains($outsider->id));
    }

    public function test_deleting_a_group_detaches_its_servers_without_deleting_them(): void
    {
        $prod = ServerGroup::create(['name' => 'prod', 'color' => 'online']);
        $server = Server::create(['name' => 'm', 'ip' => '10.0.0.1', 'ssh_port' => 22, 'status' => 'online']);
        $prod->servers()->attach($server->id);

        $prod->delete();

        $this->assertDatabaseHas('servers', ['id' => $server->id]);          // server survives
        $this->assertDatabaseMissing('server_server_group', ['server_id' => $server->id]); // pivot gone
    }
}
