<?php

namespace Tests\Feature;

use App\Livewire\Users\UserForm;
use App\Models\Company;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

class UserLocaleTest extends TestCase
{
    use RefreshDatabase;

    private function admin(): User
    {
        foreach (['create users', 'edit users'] as $p) {
            Permission::findOrCreate($p);
        }
        Role::findOrCreate('Tecnico');

        $admin = User::factory()->create();
        $admin->givePermissionTo(['create users', 'edit users']);

        return $admin;
    }

    private function company(): Company
    {
        return Company::create(['name' => 'ACME', 'estado' => 'activo', 'type' => 'constructor']);
    }

    public function test_creating_a_user_persists_the_selected_locale(): void
    {
        $admin = $this->admin();
        $company = $this->company();

        Livewire::actingAs($admin)
            ->test(UserForm::class)
            ->set('firstName', 'Ada')
            ->set('lastName', 'Lovelace')
            ->set('email', 'ada@example.com')
            ->set('companyId', $company->id)
            ->set('formRole', 'Tecnico')
            ->set('formPassword', 'Password123')
            ->set('locale', 'en')
            ->call('save');

        $this->assertDatabaseHas('users', ['email' => 'ada@example.com', 'locale' => 'en']);
    }

    public function test_editing_a_user_loads_and_updates_the_locale(): void
    {
        $admin = $this->admin();
        $company = $this->company();
        $target = User::factory()->create([
            'locale' => 'es',
            'company_id' => $company->id,
            'first_name' => 'Bob',
            'last_name' => 'Stone',
        ]);
        $target->assignRole('Tecnico');

        Livewire::actingAs($admin)
            ->test(UserForm::class, ['user' => $target])
            ->assertSet('locale', 'es')
            ->set('locale', 'en')
            ->call('save');

        $this->assertEquals('en', $target->fresh()->locale);
    }
}
