<?php

declare(strict_types=1);

use App\Services\Localization\LocaleResolver;

function unitLocaleResolver(): LocaleResolver
{
    return app(LocaleResolver::class);
}

it('resolves admin locale precedence from explicit override through system default', function (): void {
    $resolver = unitLocaleResolver();

    expect($resolver->resolveFromSources('de', 'en', 'en', 'en'))
        ->toMatchArray([
            'locale' => 'de',
            'source' => LocaleResolver::SOURCE_EXPLICIT_OVERRIDE,
            'machine_artifacts_invariant' => true,
        ]);

    expect($resolver->resolveFromSources(null, 'de', 'en', 'en'))
        ->toMatchArray([
            'locale' => 'de',
            'source' => LocaleResolver::SOURCE_USER_PREFERENCE,
        ]);

    expect($resolver->resolveFromSources(null, null, 'de', 'en'))
        ->toMatchArray([
            'locale' => 'de',
            'source' => LocaleResolver::SOURCE_WORKSPACE_DEFAULT,
        ]);

    expect($resolver->resolveFromSources(null, null, null, 'de'))
        ->toMatchArray([
            'locale' => 'de',
            'source' => LocaleResolver::SOURCE_SYSTEM_DEFAULT,
        ]);
});

it('falls through unsupported locale sources safely', function (): void {
    $resolver = unitLocaleResolver();

    $context = $resolver->resolveFromSources('fr', 'es', 'de', 'en');

    expect($context)
        ->toMatchArray([
            'locale' => 'de',
            'source' => LocaleResolver::SOURCE_WORKSPACE_DEFAULT,
            'fallback_locale' => 'en',
        ])
        ->and($context['user_preference_locale'])->toBeNull();
});

it('keeps system panel resolution to explicit override or system default only', function (): void {
    $resolver = unitLocaleResolver();

    expect($resolver->resolveFromSources(
        explicitOverride: null,
        userPreference: 'de',
        workspaceDefault: 'de',
        systemDefault: 'en',
        includeUserPreference: false,
        includeWorkspaceDefault: false,
    ))->toMatchArray([
        'locale' => 'en',
        'source' => LocaleResolver::SOURCE_SYSTEM_DEFAULT,
        'user_preference_locale' => null,
        'workspace_default_locale' => null,
    ]);

    expect($resolver->resolveFromSources(
        explicitOverride: 'de',
        userPreference: 'en',
        workspaceDefault: 'en',
        systemDefault: 'en',
        includeUserPreference: false,
        includeWorkspaceDefault: false,
    ))->toMatchArray([
        'locale' => 'de',
        'source' => LocaleResolver::SOURCE_EXPLICIT_OVERRIDE,
    ]);
});
