<?php

declare(strict_types=1);

use App\Models\Tenant;
use App\Services\Directory\RoleDefinitionsSyncService;
use App\Support\OperationRunLinks;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;

uses(RefreshDatabase::class);

it('starts a role definitions sync with an immediate canonical view link', function (): void {
    Bus::fake();

    /** @var Tenant $tenant */
    $tenant = Tenant::factory()->create([
        'app_client_id' => 'client-123',
        'app_client_secret' => 'secret',
        'status' => 'active',
    ]);

    [$user, $tenant] = createUserWithTenant($tenant, role: 'owner');

    $service = app(RoleDefinitionsSyncService::class);

    $run = $service->startManualSync($tenant, $user);

    expect($run->type)->toBe('directory_role_definitions.sync');

    $url = OperationRunLinks::tenantlessView($run);
    expect($url)->toContain('/admin/operations/');

    Bus::assertDispatched(
        App\Jobs\SyncRoleDefinitionsJob::class,
        fn (App\Jobs\SyncRoleDefinitionsJob $job): bool => $job->tenantId === (int) $tenant->getKey() && $job->operationRun?->is($run)
    );
});
