<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AuthApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_can_register_login_open_profile_and_logout(): void
    {
        $registerResponse = $this->postJson('/api/register', [
            'name' => 'Lumajang Traveler',
            'email' => 'traveler@example.com',
            'password' => 'password123',
            'password_confirmation' => 'password123',
        ]);

        $registerResponse
            ->assertCreated()
            ->assertJsonPath('success', true)
            ->assertJsonPath('data.user.email', 'traveler@example.com');

        $this->assertDatabaseHas('users', [
            'email' => 'traveler@example.com',
        ]);

        $loginResponse = $this->postJson('/api/login', [
            'email' => 'traveler@example.com',
            'password' => 'password123',
        ]);

        $loginResponse
            ->assertOk()
            ->assertJsonPath('success', true)
            ->assertJsonStructure([
                'data' => ['token_type', 'token', 'user'],
            ]);

        $token = $loginResponse->json('data.token');

        $this->getJson('/api/profile', [
            'Authorization' => "Bearer {$token}",
        ])
            ->assertOk()
            ->assertJsonPath('data.user.name', 'Lumajang Traveler');

        $this->postJson('/api/logout', [], [
            'Authorization' => "Bearer {$token}",
        ])->assertOk();

        $this->getJson('/api/profile', [
            'Authorization' => "Bearer {$token}",
        ])->assertUnauthorized();
    }

    public function test_login_rejects_wrong_password(): void
    {
        User::factory()->create([
            'email' => 'traveler@example.com',
            'password' => 'password123',
        ]);

        $this->postJson('/api/login', [
            'email' => 'traveler@example.com',
            'password' => 'wrong-password',
        ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors('email');
    }
}
