<?php

use App\Filament\Resources\ProviderConnectionResource\Pages\ListProviderConnections;
use App\Filament\Resources\ProviderConnectionResource\Pages\ViewProviderConnection;
use App\Jobs\ProviderComplianceSnapshotJob;
use App\Jobs\ProviderInventorySyncJob;
use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Services\Graph\GraphClientInterface;
use App\Support\OperationRunLinks;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;

it('dedupes inventory sync runs and does not call Graph during start', function (): void {
    Queue::fake();

    $this->mock(GraphClientInterface::class, function ($mock): void {
        $mock->shouldReceive('listPolicies')->never();
        $mock->shouldReceive('getPolicy')->never();
        $mock->shouldReceive('getOrganization')->never();
        $mock->shouldReceive('applyPolicy')->never();
        $mock->shouldReceive('getServicePrincipalPermissions')->never();
        $mock->shouldReceive('request')->never();
    });

    [$user, $tenant] = createUserWithTenant(role: 'operator', fixtureProfile: 'credential-enabled');
    $this->actingAs($user);

    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    $connection = ProviderConnection::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('provider', 'microsoft')
        ->where('is_default', true)
        ->firstOrFail();

    spec283SeedRequirementRows($tenant, ['permissions.intune_configuration', 'permissions.intune_apps']);

    $component = Livewire::test(ListProviderConnections::class);
    $component->callTableAction('inventory_sync', $connection);
    $component->callTableAction('inventory_sync', $connection);

    $opRun = OperationRun::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('type', 'inventory.sync')
        ->latest('id')
        ->first();

    expect($opRun)->not->toBeNull();
    expect($opRun?->context)->toMatchArray([
        'provider' => 'microsoft',
        'module' => 'inventory',
        'provider_connection_id' => (int) $connection->getKey(),
    ]);
    expect($opRun?->context['provider_context'] ?? [])->toMatchArray([
        'provider' => 'microsoft',
    ]);
    expect($opRun?->context['target_scope'] ?? [])->toMatchArray([
        'provider' => 'microsoft',
        'scope_kind' => 'tenant',
        'scope_identifier' => $connection->entra_tenant_id,
    ])->not->toHaveKey('entra_tenant_id');

    expect(OperationRun::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('type', 'inventory.sync')
        ->count())->toBe(1);

    Queue::assertPushed(ProviderInventorySyncJob::class, 1);
});

it('starts inventory sync from the provider connection detail page', function (): void {
    Queue::fake();

    $this->mock(GraphClientInterface::class, function ($mock): void {
        $mock->shouldReceive('listPolicies')->never();
        $mock->shouldReceive('getPolicy')->never();
        $mock->shouldReceive('getOrganization')->never();
        $mock->shouldReceive('applyPolicy')->never();
        $mock->shouldReceive('getServicePrincipalPermissions')->never();
        $mock->shouldReceive('request')->never();
    });

    [$user, $tenant] = createUserWithTenant(role: 'operator', fixtureProfile: 'credential-enabled');
    $this->actingAs($user);

    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    $connection = ProviderConnection::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('provider', 'microsoft')
        ->where('is_default', true)
        ->firstOrFail();

    spec283SeedRequirementRows($tenant, ['permissions.intune_configuration', 'permissions.intune_apps']);

    Livewire::test(ViewProviderConnection::class, ['record' => $connection->getKey()])
        ->assertActionVisible('inventory_sync')
        ->callAction('inventory_sync');

    $opRun = OperationRun::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('type', 'inventory.sync')
        ->latest('id')
        ->first();

    expect($opRun)->not->toBeNull();
    expect($opRun?->context)->toMatchArray([
        'provider' => 'microsoft',
        'module' => 'inventory',
        'provider_connection_id' => (int) $connection->getKey(),
    ]);
    expect($opRun?->context['provider_context'] ?? [])->toMatchArray([
        'provider' => 'microsoft',
    ]);
    expect($opRun?->context['target_scope'] ?? [])->toMatchArray([
        'provider' => 'microsoft',
        'scope_kind' => 'tenant',
        'scope_identifier' => $connection->entra_tenant_id,
    ])->not->toHaveKey('entra_tenant_id');

    Queue::assertPushed(ProviderInventorySyncJob::class, 1);
});

it('dedupes compliance snapshot runs and does not call Graph during start', function (): void {
    Queue::fake();

    $this->mock(GraphClientInterface::class, function ($mock): void {
        $mock->shouldReceive('listPolicies')->never();
        $mock->shouldReceive('getPolicy')->never();
        $mock->shouldReceive('getOrganization')->never();
        $mock->shouldReceive('applyPolicy')->never();
        $mock->shouldReceive('getServicePrincipalPermissions')->never();
        $mock->shouldReceive('request')->never();
    });

    [$user, $tenant] = createUserWithTenant(role: 'operator', fixtureProfile: 'credential-enabled');
    $this->actingAs($user);

    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    $connection = ProviderConnection::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('provider', 'microsoft')
        ->where('is_default', true)
        ->firstOrFail();

    spec283SeedRequirementRows($tenant, ['permissions.intune_configuration', 'permissions.intune_apps']);

    $component = Livewire::test(ListProviderConnections::class);
    $component->callTableAction('compliance_snapshot', $connection);
    $component->callTableAction('compliance_snapshot', $connection);

    $opRun = OperationRun::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('type', 'compliance.snapshot')
        ->latest('id')
        ->first();

    expect($opRun)->not->toBeNull();
    expect($opRun?->context)->toMatchArray([
        'provider' => 'microsoft',
        'module' => 'compliance',
        'provider_connection_id' => (int) $connection->getKey(),
    ]);
    expect($opRun?->context['provider_context'] ?? [])->toMatchArray([
        'provider' => 'microsoft',
    ]);
    expect($opRun?->context['target_scope'] ?? [])->toMatchArray([
        'provider' => 'microsoft',
        'scope_kind' => 'tenant',
        'scope_identifier' => $connection->entra_tenant_id,
    ])->not->toHaveKey('entra_tenant_id');

    expect(OperationRun::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('type', 'compliance.snapshot')
        ->count())->toBe(1);

    Queue::assertPushed(ProviderComplianceSnapshotJob::class, 1);
});

it('blocks different provider operations for the same scope as scope busy', function (): void {
    Queue::fake();

    [$user, $tenant] = createUserWithTenant(role: 'operator', fixtureProfile: 'credential-enabled');
    $this->actingAs($user);

    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    $connection = ProviderConnection::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('provider', 'microsoft')
        ->where('is_default', true)
        ->firstOrFail();

    spec283SeedRequirementRows($tenant, ['permissions.intune_configuration', 'permissions.intune_apps']);

    $component = Livewire::test(ListProviderConnections::class);

    $component->callTableAction('inventory_sync', $connection);
    $component->callTableAction('compliance_snapshot', $connection);

    $inventoryRun = OperationRun::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('type', 'inventory.sync')
        ->latest('id')
        ->first();

    expect($inventoryRun)->not->toBeNull();

    expect(OperationRun::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('type', 'compliance.snapshot')
        ->count())->toBe(0);

    Queue::assertPushed(ProviderInventorySyncJob::class, 1);
    Queue::assertPushed(ProviderComplianceSnapshotJob::class, 0);

    $notifications = session('filament.notifications', []);
    expect($notifications)->not->toBeEmpty();
    expect(collect($notifications)->last()['actions'][0]['url'] ?? null)
        ->toBe(OperationRunLinks::view($inventoryRun, $tenant));
});
