<?php

declare(strict_types=1);

use Builder\Core\Tests\BuilderTestUser;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;

beforeEach(function (): void {
    Schema::create('users', function ($table): void {
        $table->id();
        $table->string('name')->nullable();
        $table->string('email')->nullable()->unique();
        $table->string('locale', 10)->nullable();
        $table->string('password')->nullable();
        $table->text('two_factor_secret')->nullable();
        $table->text('two_factor_recovery_codes')->nullable();
        $table->timestamp('two_factor_confirmed_at')->nullable();
        $table->json('user_widget_preferences')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });

    config(['auth.providers.users.model' => BuilderTestUser::class]);
});

it('sets app locale from authenticated user locale column', function (): void {
    $user = BuilderTestUser::create([
        'name' => 'Dutch User',
        'email' => 'dutch@example.com',
        'password' => Hash::make('secret'),
        'locale' => 'nl',
    ]);

    $this->actingAs($user)
        ->get(route('builder.dashboard'));

    expect(app()->getLocale())->toBe('nl');
});

it('does not change locale when user has no locale set', function (): void {
    app()->setLocale('en');

    $user = BuilderTestUser::create([
        'name' => 'Jane',
        'email' => 'jane@example.com',
        'password' => Hash::make('secret'),
        'locale' => null,
    ]);

    $this->actingAs($user)
        ->get(route('builder.dashboard'));

    expect(app()->getLocale())->toBe('en');
});

it('does not change locale for unauthenticated requests', function (): void {
    app()->setLocale('en');

    $this->get(route('builder.login'));

    expect(app()->getLocale())->toBe('en');
});

it('ignores unsupported locale values', function (): void {
    app()->setLocale('en');

    $user = BuilderTestUser::create([
        'name' => 'Jane',
        'email' => 'jane@example.com',
        'password' => Hash::make('secret'),
        'locale' => 'xx',
    ]);

    $this->actingAs($user)
        ->get(route('builder.dashboard'));

    expect(app()->getLocale())->toBe('en');
});
