<?php declare(strict_types=1);

namespace Newland\NeosCommon\Tests\Unit\ConfigurationValidation;

use Neos\Flow\Tests\FunctionalTestCase;
use Newland\NeosCommon\ConfigurationValidation\ConfigurationValidationHelper;

class ConfigurationValidationHelperTest extends FunctionalTestCase
{
    protected static $testablePersistenceEnabled = true;

    /** @var ConfigurationValidationHelper */
    private $subject;

    public function setUp(): void
    {
        parent::setUp();
        $this->subject = $this->objectManager->get(ConfigurationValidationHelper::class);
    }

    /**
     * @dataProvider providePrivileges
     * @param string|null $errorToExpect
     * @param array $policies
     */
    public function testPoliciesAreCheckedForExpensiveOperations(?string $errorToExpect, array $policies): void
    {
        $this->inject($this->subject, 'policies', $policies);

        $result = $this->subject->getAdditionalValidationResults();
        if ($errorToExpect === null) {
            $this->assertFalse($result->hasErrors(), 'Result should not have any errors');
        } else {
            $this->assertTrue($result->hasErrors(), 'Result should have errors');
            $this->assertContains($errorToExpect, $result->getErrors()[0]->render());
        }
    }


    public function providePrivileges(): array
    {
        return [

            'has invalid uuid selector' => [
                'Policy.privilegeTargets.Neos\ContentRepository\Security\Authorization\Privilege\Node\EditNodePrivilege.Newland:AutTheme:EditWater',
                [
                    'privilegeTargets' => [
                        'Neos\ContentRepository\Security\Authorization\Privilege\Node\EditNodePrivilege' => [
                            'Newland:AutTheme:EditWater' => [
                                'matcher' => 'isDescendantNodeOf("93c96eac-4f66-41ce-a8e1-77482f5a5475")',
                            ],
                        ],
                    ],
                ],
            ],

            'has valid path selector' => [
                null,
                [
                    'privilegeTargets' => [
                        'Neos\ContentRepository\Security\Authorization\Privilege\Node\EditNodePrivilege' => [
                            'Newland:AutTheme:EditWater' => [
                                'matcher' => 'isDescendantNodeOf("/sites/oehningen")',
                            ],
                        ],
                    ],
                ]
            ]
        ];
    }

}