<?php

use App\Models\AuditLog;
use App\Filament\Resources\ProviderConnectionResource;
use App\Filament\Resources\ProviderConnectionResource\Pages\EditProviderConnection;
use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Models\ProviderCredential;
use App\Support\Providers\ProviderConsentStatus;
use App\Support\Providers\ProviderReasonCodes;
use App\Support\Providers\ProviderVerificationStatus;
use Filament\Facades\Filament;
use Livewire\Livewire;

it('enables a disabled connection and records verification as blocked when credentials are missing', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);

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

    $connection = ProviderConnection::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'provider' => 'microsoft',
        'entra_tenant_id' => fake()->uuid(),
        'is_enabled' => false,
        'consent_status' => ProviderConsentStatus::Granted->value,
        'verification_status' => ProviderVerificationStatus::Error->value,
        'last_health_check_at' => now(),
        'last_error_reason_code' => 'provider_auth_failed',
        'last_error_message' => 'Some failure',
    ]);

    Livewire::test(EditProviderConnection::class, ['record' => $connection->getRouteKey()])
        ->callAction('enable_connection');

    $connection->refresh();
    $audit = AuditLog::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('action', 'provider_connection.enabled')
        ->latest('id')
        ->first();

    expect($connection->is_enabled)->toBeTrue()
        ->and($connection->consent_status)->toBe(ProviderConsentStatus::Granted)
        ->and($connection->verification_status)->toBe(ProviderVerificationStatus::Blocked)
        ->and($connection->last_health_check_at)->toBeNull()
        ->and($connection->last_error_reason_code)->toBe(ProviderReasonCodes::ProviderCredentialMissing)
        ->and($connection->last_error_message)->toBe('Provider connection credentials are missing.');

    expect($audit)->not->toBeNull()
        ->and($audit?->metadata['from_lifecycle'] ?? null)->toBe('disabled')
        ->and($audit?->metadata['to_lifecycle'] ?? null)->toBe('enabled')
        ->and($audit?->metadata['verification_status'] ?? null)->toBe(ProviderVerificationStatus::Blocked->value)
        ->and($audit?->metadata['credentials_present'] ?? null)->toBeFalse();
});

it('enables a disabled connection and resets verification when credentials are present', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);

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

    $connection = ProviderConnection::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'provider' => 'microsoft',
        'entra_tenant_id' => fake()->uuid(),
        'is_enabled' => false,
        'consent_status' => ProviderConsentStatus::Granted->value,
        'verification_status' => ProviderVerificationStatus::Error->value,
    ]);

    ProviderCredential::factory()->create([
        'provider_connection_id' => $connection->getKey(),
        'payload' => [
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
        ],
    ]);

    Livewire::test(EditProviderConnection::class, ['record' => $connection->getRouteKey()])
        ->callAction('enable_connection');

    $connection->refresh();
    $audit = AuditLog::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('action', 'provider_connection.enabled')
        ->latest('id')
        ->first();

    expect($connection->is_enabled)->toBeTrue()
        ->and($connection->consent_status)->toBe(ProviderConsentStatus::Granted)
        ->and($connection->verification_status)->toBe(ProviderVerificationStatus::Unknown);

    expect($audit)->not->toBeNull()
        ->and($audit?->metadata['from_lifecycle'] ?? null)->toBe('disabled')
        ->and($audit?->metadata['to_lifecycle'] ?? null)->toBe('enabled')
        ->and($audit?->metadata['verification_status'] ?? null)->toBe(ProviderVerificationStatus::Unknown->value)
        ->and($audit?->metadata['credentials_present'] ?? null)->toBeTrue();
});

it('disables an enabled connection without changing consent or verification truth', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);

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

    $connection = ProviderConnection::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'provider' => 'microsoft',
        'entra_tenant_id' => fake()->uuid(),
        'is_enabled' => true,
        'consent_status' => ProviderConsentStatus::Granted->value,
        'verification_status' => ProviderVerificationStatus::Healthy->value,
    ]);

    Livewire::test(EditProviderConnection::class, ['record' => $connection->getRouteKey()])
        ->callAction('disable_connection');

    $connection->refresh();
    $audit = AuditLog::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('action', 'provider_connection.disabled')
        ->latest('id')
        ->first();

    expect($connection->is_enabled)->toBeFalse()
        ->and($connection->consent_status)->toBe(ProviderConsentStatus::Granted)
        ->and($connection->verification_status)->toBe(ProviderVerificationStatus::Healthy);

    expect($audit)->not->toBeNull()
        ->and($audit?->metadata['from_lifecycle'] ?? null)->toBe('enabled')
        ->and($audit?->metadata['to_lifecycle'] ?? null)->toBe('disabled');
});

it('shows a link to the last connection check run when present', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $connection = ProviderConnection::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'provider' => 'microsoft',
        'entra_tenant_id' => fake()->uuid(),
    ]);

    $run = OperationRun::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'user_id' => $user->getKey(),
        'initiator_name' => $user->name,
        'type' => 'provider.connection.check',
        'status' => 'completed',
        'outcome' => 'succeeded',
        'context' => [
            'provider' => 'microsoft',
            'module' => 'health_check',
            'provider_connection_id' => (int) $connection->getKey(),
            'target_scope' => [
                'entra_tenant_id' => $connection->entra_tenant_id,
            ],
        ],
    ]);

    $this->actingAs($user)
        ->get(ProviderConnectionResource::getUrl('edit', ['record' => $connection], tenant: $tenant))
        ->assertOk();
});
