<?php

use App\Livewire\Admin\EditExportTarget;
use App\Models\ExportTarget;
use App\Services\Secrets\SecretCipher;
use Livewire\Livewire;

it('shows host, port and user only once SFTP is chosen', function () {
    $c = Livewire::actingAs(operator('Owner'), 'operator')->test(EditExportTarget::class);

    // A mounted directory has no host: the mount is made on the server with
    // mount(8), and the application only names the directory it writes into.
    $c->assertDontSee(__('finance.target.host'))
        ->assertSee(__('finance.target.path'));

    $c->set('driver', 'sftp')
        ->assertSee(__('finance.target.host'))
        ->assertSee(__('finance.target.port'))
        ->assertSee(__('finance.target.username'))
        ->assertSee(__('finance.target.password'));
});

it('stores an SFTP destination with its host and keeps the password out of the row', function () {
    Livewire::actingAs(operator('Owner'), 'operator')
        ->test(EditExportTarget::class)
        ->set('name', 'Storage Box')
        ->set('driver', 'sftp')
        ->set('host', 'u123456.your-storagebox.de')
        ->set('port', 23)
        ->set('username', 'u123456')
        ->set('password', 'geheim')
        ->set('path', '/rechnungen')
        ->call('save')
        ->assertHasNoErrors();

    $target = ExportTarget::query()->where('name', 'Storage Box')->firstOrFail();

    expect($target->host)->toBe('u123456.your-storagebox.de')
        ->and($target->port)->toBe(23)
        ->and($target->username)->toBe('u123456')
        // Stored encrypted, never in the clear — a credential in a settings
        // table in plain text is a credential in every database dump.
        ->and($target->secret_key)->not->toBe('geheim')
        ->and($target->secret_key)->not->toBeEmpty()
        ->and(app(SecretCipher::class)->decrypt($target->secret_key))->toBe('geheim');
});
