<?php

namespace Tests\Feature\Accounts;

use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Hash;
use PHPUnit\Framework\Attributes\Group;
use App\Models\User;
use Tests\TestCase;

#[Group('unit')]
#[Group('segments')]
#[Group('services')]
#[Group('ok_to_run')]
class AuthenticationTest extends TestCase
{
    // use DatabaseTransactions;

    /**
     * Test user can successfully authenticate with valid credentials.
     *
     * @return void
     */
    public function test_user_can_authenticate_with_valid_credentials()
    {
        // A R R A N G E
        $email = 'test_user_can_authenticate_with_valid_credentials@example.com';
        $user = User::where('email', $email)->first();
        if (!$user) {
            $user = new User();
            $user->email = $email;
        }
        $user->name = 'test_user_can_authenticate_with_valid_credentials';
        $user->password = Hash::make('password123');
        $user->type = \App\Classes\ValueObjects\Constants\RoleTypes::ADMIN;
        $user->status = 1;
        $user->save();

        // A C T: Hit the login attempt API
        $response = $this->postJson('/api/v1/account/authentication/login/attempt', [
            'email' => $email,
            'password' => 'password123',
        ]);

        // A S S E R T: Expect 200 OK and a JSON payload structure
        $response->assertStatus(200)
            ->assertJsonStructure([
                'payload' => [
                    'access_token',
                    'redirect_url'
                ]
            ]);
    }

    /**
     * Test user cannot authenticate with invalid password.
     *
     * @return void
     */
    public function test_user_cannot_authenticate_with_invalid_credentials()
    {
        // A R R A N G E
        $email = 'test_user_cannot_authenticate_with_invalid_credentials@example.com';
        $user = User::where('email', $email)->first();
        if (!$user) {
            $user = new User();
            $user->email = $email;
        }
        $user->name = 'test_user_cannot_authenticate_with_invalid_credentials';
        $user->password = Hash::make('password123');
        $user->type = \App\Classes\ValueObjects\Constants\RoleTypes::ADMIN;
        $user->status = 1;
        $user->save();

        // A C T
        $response = $this->postJson('/api/v1/account/authentication/login/attempt', [
            'email' => $email,
            'password' => 'wrongpassword',
        ]);

        // A S S E R T
        // Unprocessable Entity or Unauthorized depending on application logic
        // 400/401/422 are common. Let's assert it just doesn't succeed (not 200)
        $this->assertNotEquals(200, $response->getStatusCode());
    }
}
