<?php

use Beebmx\KirbySign\Actions\GenerateKeyCommand;
use Kirby\CLI\CLI;
use Kirby\Filesystem\F;

beforeEach(function () {
    App();
    $this->cli = new CLI;
});

it('can generate a key', function () {
    expect($this->cli->commands()['plugins'])
        ->toContain('key:generate');
});

it('can be executed key:generate command', function () {
    CLI::command('key:generate');
})->throwsNoExceptions();

it('generates a new random key', function () {
    $this->cli->climate()->output->defaultTo('buffer');

    (new GenerateKeyCommand)($this->cli);

    $output = $this->cli
        ->climate()
        ->output
        ->get('buffer')
        ->get();

    expect($output)
        ->toContain('base64:')
        ->toContain('Key generated successfully');
});

it('wont update if no KIRBY_KEY value is present', function () {
    copyEnv('.env.invalid');

    CLI::command('key:generate', '--env');

    expect(F::read(getPathFor('.env')))
        ->not->toContain('KIRBY_KEY=')
        ->not->toContain('KIRBY_KEY=base64:');

    deleteEnv();
});

it('can set KIRBY_KEY value', function () {
    copyEnv();

    CLI::command('key:generate', '--env');

    expect(F::read(getPathFor('.env')))
        ->toContain('KIRBY_KEY=')
        ->toContain('KIRBY_KEY=base64:');

    deleteEnv();
});

it('can replace KIRBY_KEY value', function () {
    copyEnv('.env.filled');

    CLI::command('key:generate', '--env');

    expect(F::read(getPathFor('.env')))
        ->toContain('KIRBY_KEY=')
        ->toContain('KIRBY_KEY=base64:')
        ->not->toContain('base64:HA4EkKQMHxCgUfXEYYcLH24W9AStAavif8GmmoikhZQ=')
        ->and(F::read(getPathFor('.env')))
        ->not->toEqual(F::read(getPathFor('.env.filled')));

    deleteEnv();
});

it('can set KIRBY_KEY in defined path', function () {
    copyEnv(path: 'env/');

    CLI::command('key:generate', '--env', 'path='.getPathFor('env/'));

    expect(F::read(getPathFor('env/.env')))
        ->toContain('KIRBY_KEY=')
        ->toContain('KIRBY_KEY=base64:');

    deleteEnv(path: 'env/');
});

it('can set KIRBY_KEY in defined PATH argument as uppercase', function () {
    copyEnv(path: 'env/');

    CLI::command('key:generate', '--env', 'PATH='.getPathFor('env/'));

    expect(F::read(getPathFor('env/.env')))
        ->toContain('KIRBY_KEY=')
        ->toContain('KIRBY_KEY=base64:');

    deleteEnv(path: 'env/');
});
