<?php

use App\Models\EntraGroup;
use App\Models\ManagedEnvironment;
use App\Services\Directory\EntraGroupLabelResolver;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('formats unresolved labels using an ellipsis + last 8 chars', function () {
    $id = '11111111-2222-3333-4444-555555555555';

    expect(EntraGroupLabelResolver::formatLabel(null, $id))
        ->toBe('Unresolved (…55555555)');
});

it('resolves labels from the tenant cache (tenant-scoped)', function () {
    $tenantA = ManagedEnvironment::factory()->create();
    $tenantB = ManagedEnvironment::factory()->create();

    $entraId = '11111111-2222-3333-4444-555555555555';

    EntraGroup::factory()->create([
        'managed_environment_id' => $tenantA->getKey(),
        'entra_id' => $entraId,
        'display_name' => 'Alpha Team',
    ]);

    EntraGroup::factory()->create([
        'managed_environment_id' => $tenantB->getKey(),
        'entra_id' => $entraId,
        'display_name' => 'Beta Team',
    ]);

    $resolver = app(EntraGroupLabelResolver::class);

    expect($resolver->resolveOne($tenantA, $entraId))
        ->toBe('Alpha Team (…55555555)')
        ->and($resolver->resolveOne($tenantB, $entraId))
        ->toBe('Beta Team (…55555555)');
});

it('returns a fallback without querying invalid UUIDs', function () {
    $tenant = ManagedEnvironment::factory()->create();

    $resolver = app(EntraGroupLabelResolver::class);

    expect($resolver->resolveOne($tenant, 'group-123'))
        ->toBe('Unresolved (group123)');
});
