<?php

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Modules\Identity\Enums\TokenAbility;

test('customer token endpoint issues a token with the full customer ability set', function () {
    $user = User::factory()->create([
        'password' => Hash::make('secret-password'),
    ]);

    $response = $this->postJson('/api/v1/auth/token', [
        'email' => $user->email,
        'password' => 'secret-password',
        'device_name' => 'iphone',
    ]);

    $response->assertSuccessful()->assertJsonStructure(['token']);

    $accessToken = $user->tokens()->sole();
    expect($accessToken->abilities)->toEqualCanonicalizing(TokenAbility::customerAbilities());
});

test('customer token endpoint rejects invalid credentials', function () {
    $user = User::factory()->create([
        'password' => Hash::make('secret-password'),
    ]);

    $response = $this->postJson('/api/v1/auth/token', [
        'email' => $user->email,
        'password' => 'wrong-password',
        'device_name' => 'iphone',
    ]);

    $response->assertUnprocessable();
    expect($user->tokens()->count())->toBe(0);
});

test('identity:issue-agent-token command provisions a token scoped to the agent ability set', function () {
    $this->artisan('identity:issue-agent-token')->assertSuccessful();

    $agent = User::where('email', 'fastapi-agent@system.internal')->sole();
    $token = $agent->tokens()->sole();

    expect($token->abilities)->toEqualCanonicalizing(TokenAbility::fastApiAgentAbilities());
});
