<?php

use Carbon\Carbon;
use Kirby\Cms\App;
use Kirby\Toolkit\Str;

describe('query', function () {
    beforeEach(function () {
        App(options: ['beebmx.kirby-sign' => ['key' => 'test-key']]);
    });

    test('a page can be signed', function () {
        $page = App::instance()->page('secure');

        expect($page->signed())
            ->toContain('signature');
    });

    test('a page can have parameters', function () {
        $page = App::instance()->page('secure');

        expect($page->signed(['foo' => 'bar']))
            ->toContain('foo=bar');
    });

    test('a page can have expiration time', function () {
        $page = App::instance()->page('secure');

        expect($page->signed(expiration: Carbon::now()->addHour()))
            ->toContain('expires');
    });

    test('a page can have parameters and expiration time', function () {
        $page = App::instance()->page('secure');

        expect($page->signed(['foo' => 'bar', 'baz' => 'qux'], expiration: Carbon::now()->addHour()))
            ->toContain('foo=bar', 'baz=qux')
            ->toContain('expires');
    });
});

describe('query validation', function () {
    beforeEach(function () {
        App(options: ['beebmx.kirby-sign' => ['key' => 'test-key']]);
        $this->page = App::instance()->page('secure');
        $expires = $this->page->signed(expiration: Carbon::now()->addHour());

        $uri = Str::replace($expires, App::instance()->url(), '');
        App::destroy();
        App(options: ['beebmx.kirby-sign' => ['key' => 'test-key']], uri: $uri);
    });

    test('a page can be valid', function () {
        expect($this->page->hasValidSignature())
            ->toBeTrue();
    });

    test('a page can expires', function () {
        expect($this->page->hasValidSignature())
            ->toBeTrue();

        Carbon::setTestNow(Carbon::now()->addHour()->addSecond());

        expect($this->page->hasValidSignature())
            ->toBeFalse();
    });

    test('a page without signature is invalid', function () {
        $uri = Str::replace($this->page->url(), App::instance()->url(), '');
        App::destroy();
        App(options: ['beebmx.kirby-sign' => ['key' => 'test-key']], uri: $uri);

        expect($this->page->hasValidSignature())
            ->toBeFalse();
    });
});
