<?php

declare(strict_types=1);

use App\Models\AuditLog;
use App\Models\ManagedEnvironment;
use App\Models\TenantSetting;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Services\Settings\SettingsWriter;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

it('rejects tenant override writes when tenant does not belong to the provided workspace', function (): void {
    $workspaceA = Workspace::factory()->create();
    $workspaceB = Workspace::factory()->create();

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

    $user = User::factory()->create();

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $workspaceA->getKey(),
        'user_id' => (int) $user->getKey(),
        'role' => 'manager',
    ]);

    $writer = app(SettingsWriter::class);

    expect(fn () => $writer->updateTenantSetting(
        actor: $user,
        workspace: $workspaceA,
        tenant: $tenantInWorkspaceB,
        domain: 'backup',
        key: 'retention_keep_last_default',
        value: 7,
    ))->toThrow(NotFoundHttpException::class);

    expect(TenantSetting::query()->count())->toBe(0);
    expect(AuditLog::query()->count())->toBe(0);
});
