<?php

declare(strict_types=1);

use App\Filament\Resources\EntraGroupResource;
use App\Models\EntraGroup;
use Filament\Facades\Filament;
use Illuminate\Testing\TestResponse;

function visibleGroupDetailText(TestResponse $response): string
{
    $html = (string) $response->getContent();
    $html = preg_replace('/<script\b[^>]*>.*?<\/script>/is', '', $html) ?? $html;
    $html = preg_replace('/<style\b[^>]*>.*?<\/style>/is', '', $html) ?? $html;
    $html = preg_replace('/\s+wire:snapshot="[^"]*"/', '', $html) ?? $html;
    $html = preg_replace('/\s+wire:effects="[^"]*"/', '', $html) ?? $html;

    return trim((string) preg_replace('/\s+/', ' ', strip_tags($html)));
}

it('renders directory groups with identity and classification before technical detail', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);

    Filament::setTenant($tenant, true);

    $group = EntraGroup::factory()->for($tenant)->create([
        'display_name' => 'Group One',
        'entra_id' => '11111111-2222-3333-4444-555555555555',
        'group_types' => ['Unified'],
        'security_enabled' => true,
        'mail_enabled' => false,
    ]);

    $response = $this->get(EntraGroupResource::getUrl('view', ['record' => $group], tenant: $tenant))
        ->assertOk()
        ->assertSee('Directory identity')
        ->assertSee('Freshness')
        ->assertSee('Microsoft 365')
        ->assertSeeInOrder(['Group One', 'Classification overview', 'Related context', 'Technical detail']);

    $pageText = visibleGroupDetailText($response);

    expect($pageText)->not->toContain('Security enabled Yes Enabled')
        ->and($pageText)->not->toContain('Mail enabled No Disabled');
});

it('renders an explicit empty related-context state for sparse groups', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);

    Filament::setTenant($tenant, true);

    $group = EntraGroup::factory()->for($tenant)->create([
        'display_name' => 'Sparse group',
        'group_types' => [],
        'security_enabled' => false,
        'mail_enabled' => false,
        'last_seen_at' => null,
    ]);

    $this->get(EntraGroupResource::getUrl('view', ['record' => $group], tenant: $tenant))
        ->assertOk()
        ->assertSee('No related context is available for this record.')
        ->assertSee('Classification overview')
        ->assertSee('Technical detail');
});
