<?php

declare(strict_types=1);

use App\Models\Workspace;
use App\Models\WorkspaceSetting;
use App\Services\Settings\SettingsResolver;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

uses(RefreshDatabase::class);

it('caches repeated workspace setting resolution within a request', function (): void {
    $workspace = Workspace::factory()->create();

    WorkspaceSetting::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'domain' => 'backup',
        'key' => 'retention_keep_last_default',
        'value' => 41,
        'updated_by_user_id' => null,
    ]);

    $resolver = app(SettingsResolver::class);

    DB::flushQueryLog();
    DB::enableQueryLog();

    expect($resolver->resolveValue($workspace, 'backup', 'retention_keep_last_default'))->toBe(41);
    expect($resolver->resolveValue($workspace, 'backup', 'retention_keep_last_default'))->toBe(41);

    $workspaceSettingsQueries = collect(DB::getQueryLog())
        ->pluck('query')
        ->filter(fn (string $query): bool => str_contains($query, 'workspace_settings'))
        ->count();

    expect($workspaceSettingsQueries)->toBe(1);
});

it('resolves tenant override from cache without repeated database reads', function (): void {
    $workspace = Workspace::factory()->create();
    $tenant = \App\Models\ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
    ]);

    WorkspaceSetting::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'domain' => 'backup',
        'key' => 'retention_keep_last_default',
        'value' => 22,
        'updated_by_user_id' => null,
    ]);

    \App\Models\TenantSetting::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'managed_environment_id' => (int) $tenant->getKey(),
        'domain' => 'backup',
        'key' => 'retention_keep_last_default',
        'value' => 12,
        'updated_by_user_id' => null,
    ]);

    $resolver = app(SettingsResolver::class);

    DB::flushQueryLog();
    DB::enableQueryLog();

    expect($resolver->resolveValue($workspace, 'backup', 'retention_keep_last_default', $tenant))->toBe(12);
    expect($resolver->resolveValue($workspace, 'backup', 'retention_keep_last_default', $tenant))->toBe(12);

    $settingsQueries = collect(DB::getQueryLog())
        ->pluck('query')
        ->filter(fn (string $query): bool => str_contains($query, 'tenant_settings') || str_contains($query, 'workspace_settings'))
        ->count();

    expect($settingsQueries)->toBe(2);
});
