<?php

use App\Models\AuditLog;
use App\Models\ManagedEnvironment;
use App\Models\Workspace;
use App\Services\Intune\AuditLogger;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

it('stores workspace_id for tenant scoped audit writes', function (): void {
    $workspace = Workspace::factory()->create();

    $tenant = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
    ]);

    $log = app(AuditLogger::class)->log(
        tenant: $tenant,
        action: 'workspace_isolation.audit_logger_test',
        context: ['source' => 'test'],
        status: 'success',
    );

    expect((int) $log->managed_environment_id)->toBe((int) $tenant->getKey());
    expect((int) $log->workspace_id)->toBe((int) $workspace->getKey());
});

it('allows workspace only and platform only audit scopes', function (): void {
    $workspace = Workspace::factory()->create();

    $workspaceScoped = AuditLog::query()->create([
        'managed_environment_id' => null,
        'workspace_id' => (int) $workspace->getKey(),
        'actor_id' => null,
        'actor_email' => null,
        'actor_name' => null,
        'action' => 'workspace_isolation.workspace_scope',
        'resource_type' => 'workspace',
        'resource_id' => (string) $workspace->getKey(),
        'status' => 'success',
        'metadata' => [],
        'recorded_at' => now(),
    ]);

    $platformScoped = AuditLog::query()->create([
        'managed_environment_id' => null,
        'workspace_id' => null,
        'actor_id' => null,
        'actor_email' => null,
        'actor_name' => null,
        'action' => 'workspace_isolation.platform_scope',
        'resource_type' => null,
        'resource_id' => null,
        'status' => 'success',
        'metadata' => [],
        'recorded_at' => now(),
    ]);

    expect($workspaceScoped->exists)->toBeTrue();
    expect($platformScoped->exists)->toBeTrue();
});

it('rejects tenant scoped audit rows without workspace_id at the database layer', function (): void {
    if (DB::getDriverName() === 'sqlite') {
        $this->markTestSkipped('Audit scope check constraint is enforced on pgsql/mysql migrations.');
    }

    $workspace = Workspace::factory()->create();

    $tenant = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
    ]);

    expect(fn () => DB::table('audit_logs')->insert([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => null,
        'actor_id' => null,
        'actor_email' => null,
        'actor_name' => null,
        'action' => 'workspace_isolation.invalid_scope',
        'resource_type' => 'tenant',
        'resource_id' => (string) $tenant->getKey(),
        'status' => 'failed',
        'metadata' => json_encode([], JSON_THROW_ON_ERROR),
        'recorded_at' => now(),
        'created_at' => now(),
        'updated_at' => now(),
    ]))->toThrow(QueryException::class);
});
