<?php

namespace Tests\Feature\API;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\Hash;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class AuthenticationTest extends TestCase
{
    use RefreshDatabase, WithFaker;

    public function test_user_can_login(): void
    {
        $password = 'lpc..pwd';
        $user = User::factory()->create([
            'password' => Hash::make($password),
            'username' => 'lpc',
        ]);

        $fields = ['username', 'email'];

        foreach($fields as $field) {
            $response = $this->post('/api/login', [
                'username' => $user->$field,
                'password' => $password,
            ]);

            $response->assertStatus(200);

            $response->assertJsonIsObject("data");

            $response->assertJson([
                'data' => [
                    'token' => true,
                ]
            ]);
        }
    }

    public function test_user_can_logout(): void
    {
        $user = User::factory()->create([
            'username' => 'lpc'
        ]);

        Sanctum::actingAs($user);

        $response = $this->post('/api/logout');

        $response->assertStatus(204);
    }
}