<?php

use App\Jobs\TestMailProfileConnection;
use App\Models\MailProfile;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\Queue;

function adminUserSecurity(): User
{
    $user = User::factory()->create();
    $role = Role::firstOrCreate(['slug' => 'admin'], ['name' => 'Admin']);
    Permission::firstOrCreate(['slug' => 'manage-settings'], ['name' => 'Manage Settings']);
    $user->roles()->syncWithoutDetaching([$role->id]);

    return $user;
}

it('does not leak encrypted_password in json endpoint', function () {
    $user = adminUserSecurity();
    test()->actingAs($user);
    $profile = MailProfile::factory()->create(['name' => 'SecureProfile']);
    $resp = test()->get(route('admin.mail-profiles.json'));
    $resp->assertSuccessful();
    $resp->assertJsonMissingPath('0.encrypted_password');
    $resp->assertJsonFragment(['name' => 'SecureProfile']);
});

it('queues test connection job and updates queued status', function () {
    Queue::fake();
    $user = adminUserSecurity();
    test()->actingAs($user);
    $profile = MailProfile::factory()->create(['test_status' => null]);
    $resp = test()->post(route('admin.mail-profiles.test', $profile));
    $resp->assertRedirect();
    $profile->refresh();
    expect($profile->test_status)->toBe('queued');
    Queue::assertPushed(TestMailProfileConnection::class, function ($job) use ($profile) {
        return $job->mailProfileId === $profile->id;
    });
});
