<?php

namespace Tests\Feature;

use App\Models\Divisi;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;

class ProfileFlowTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_can_view_profile_page(): void
    {
        $user = User::factory()->create(['role' => 'user']);

        $response = $this->actingAs($user)->get(route('profile.index'));

        $response->assertOk();
    }

    public function test_user_can_update_profile_information(): void
    {
        $divisiA = Divisi::create(['nama' => 'Divisi A']);
        $divisiB = Divisi::create(['nama' => 'Divisi B']);
        $user = User::factory()->create([
            'name' => 'Nama Lama',
            'email' => 'lama@example.com',
            'divisi_id' => $divisiA->id,
            'phone' => '0811111111',
        ]);

        $response = $this->actingAs($user)->patch(route('profile.update'), [
            'name' => 'Nama Baru',
            'email' => 'baru@example.com',
            'phone' => '0822222222',
            'divisi_id' => $divisiB->id,
        ]);

        $response->assertRedirect(route('profile.edit'));
        $response->assertSessionHas('status', 'profile-updated');
        $this->assertDatabaseHas('users', [
            'id' => $user->id,
            'name' => 'Nama Baru',
            'email' => 'baru@example.com',
            'phone' => '0822222222',
            'divisi_id' => $divisiB->id,
        ]);
    }

    public function test_user_can_update_password(): void
    {
        $user = User::factory()->create([
            'password' => Hash::make('OldPass123!'),
            'password_changed_at' => now()->subMonth(),
        ]);
        $previousPasswordChangedAt = $user->password_changed_at;

        $response = $this->actingAs($user)->put(route('profile.password.update'), [
            'current_password' => 'OldPass123!',
            'password' => 'NewPass123!',
            'password_confirmation' => 'NewPass123!',
        ]);

        $response->assertSessionHas('status', 'password-updated');
        $freshUser = $user->fresh();
        $this->assertTrue(Hash::check('NewPass123!', $freshUser->password));
        $this->assertTrue($freshUser->password_changed_at->greaterThan($previousPasswordChangedAt));
    }

    public function test_login_history_route_redirects_back_to_profile(): void
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user)->get(route('profile.login-history'));

        $response->assertRedirect(route('profile.index'));
    }
}
