<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\DocStoreBundle\Tests\Security\Authorization;

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Repository\AssociatedEntityToStoredObjectInterface;
use Chill\DocStoreBundle\Security\Authorization\StoredObjectRoleEnum;
use Chill\DocStoreBundle\Security\Authorization\StoredObjectVoter\AbstractStoredObjectVoter;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Workflow\Helper\WorkflowRelatedEntityPermissionHelper;
use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Bundle\SecurityBundle\Security;

/**
 * @internal
 *
 * @coversNothing
 */
class AbstractStoredObjectVoterTest extends TestCase
{
    use ProphecyTrait;

    private function buildStoredObjectVoter(
        bool $canBeAssociatedWithWorkflow,
        AssociatedEntityToStoredObjectInterface $repository,
        Security $security,
        ?WorkflowRelatedEntityPermissionHelper $workflowDocumentService = null,
    ): AbstractStoredObjectVoter {
        // Anonymous class extending the abstract class
        return new class ($canBeAssociatedWithWorkflow, $repository, $security, $workflowDocumentService) extends AbstractStoredObjectVoter {
            public function __construct(
                private readonly bool $canBeAssociatedWithWorkflow,
                private readonly AssociatedEntityToStoredObjectInterface $repository,
                Security $security,
                ?WorkflowRelatedEntityPermissionHelper $workflowDocumentService = null,
            ) {
                parent::__construct($security, $workflowDocumentService);
            }

            protected function attributeToRole($attribute): string
            {
                return 'SOME_ROLE';
            }

            protected function getRepository(): AssociatedEntityToStoredObjectInterface
            {
                return $this->repository;
            }

            protected function getClass(): string
            {
                return \stdClass::class;
            }

            protected function canBeAssociatedWithWorkflow(): bool
            {
                return $this->canBeAssociatedWithWorkflow;
            }
        };
    }

    public function testSupportsOnAttribute(): void
    {
        $voter = $this->buildStoredObjectVoter(false, new DummyRepository(new \stdClass()), $this->prophesize(Security::class)->reveal(), null);

        self::assertTrue($voter->supports(StoredObjectRoleEnum::SEE, new StoredObject()));

        $voter = $this->buildStoredObjectVoter(false, new DummyRepository(new User()), $this->prophesize(Security::class)->reveal(), null);

        self::assertFalse($voter->supports(StoredObjectRoleEnum::SEE, new StoredObject()));

        $voter = $this->buildStoredObjectVoter(false, new DummyRepository(null), $this->prophesize(Security::class)->reveal(), null);

        self::assertFalse($voter->supports(StoredObjectRoleEnum::SEE, new StoredObject()));
    }

    /**
     * @dataProvider dataProviderVoteOnAttribute
     */
    public function testVoteOnAttribute(
        StoredObjectRoleEnum $attribute,
        bool $expected,
        bool $canBeAssociatedWithWorkflow,
        bool $isGrantedRegularPermission,
        ?string $isGrantedWorkflowPermissionRead,
        ?string $isGrantedWorkflowPermissionWrite,
        string $message,
    ): void {
        $storedObject = new StoredObject();
        $dummyRepository = new DummyRepository($related = new \stdClass());
        $token = new UsernamePasswordToken(new User(), 'dummy');

        $security = $this->prophesize(Security::class);
        $security->isGranted('SOME_ROLE', $related)->willReturn($isGrantedRegularPermission);

        $workflowRelatedEntityPermissionHelper = $this->prophesize(WorkflowRelatedEntityPermissionHelper::class);
        if (null !== $isGrantedWorkflowPermissionRead) {
            $workflowRelatedEntityPermissionHelper->isAllowedByWorkflowForReadOperation($related)
                ->willReturn($isGrantedWorkflowPermissionRead)->shouldBeCalled();
        } else {
            $workflowRelatedEntityPermissionHelper->isAllowedByWorkflowForReadOperation($related)->shouldNotBeCalled();
        }

        if (null !== $isGrantedWorkflowPermissionWrite) {
            $workflowRelatedEntityPermissionHelper->isAllowedByWorkflowForWriteOperation($related)
                ->willReturn($isGrantedWorkflowPermissionWrite)->shouldBeCalled();
        } else {
            $workflowRelatedEntityPermissionHelper->isAllowedByWorkflowForWriteOperation($related)->shouldNotBeCalled();
        }

        $voter = $this->buildStoredObjectVoter($canBeAssociatedWithWorkflow, $dummyRepository, $security->reveal(), $workflowRelatedEntityPermissionHelper->reveal());
        self::assertEquals($expected, $voter->voteOnAttribute($attribute, $storedObject, $token), $message);
    }

    public static function dataProviderVoteOnAttribute(): iterable
    {
        // not associated on a workflow
        yield [StoredObjectRoleEnum::SEE, true, false, true, null, null, 'not associated on a workflow, granted by regular access, must not rely on helper'];
        yield [StoredObjectRoleEnum::SEE, false, false, false, null, null, 'not associated on a workflow, denied by regular access, must not rely on helper'];

        // associated on a workflow, read operation
        yield [StoredObjectRoleEnum::SEE, true, true, true, WorkflowRelatedEntityPermissionHelper::FORCE_GRANT, null, 'associated on a workflow, read by regular, force grant by workflow, ask for read, should be granted'];
        yield [StoredObjectRoleEnum::SEE, true, true, true, WorkflowRelatedEntityPermissionHelper::ABSTAIN, null, 'associated on a workflow, read by regular, abstain by workflow, ask for read, should be granted'];
        yield [StoredObjectRoleEnum::SEE, false, true, true, WorkflowRelatedEntityPermissionHelper::FORCE_DENIED, null, 'associated on a workflow, read by regular, force grant by workflow, ask for read, should be denied'];
        yield [StoredObjectRoleEnum::SEE, true, true, false, WorkflowRelatedEntityPermissionHelper::FORCE_GRANT, null, 'associated on a workflow, denied read by regular, force grant by workflow, ask for read, should be granted'];
        yield [StoredObjectRoleEnum::SEE, false, true, false, WorkflowRelatedEntityPermissionHelper::ABSTAIN, null, 'associated on a workflow, denied read by regular, abstain by workflow, ask for read, should be granted'];
        yield [StoredObjectRoleEnum::SEE, false, true, false, WorkflowRelatedEntityPermissionHelper::FORCE_DENIED, null, 'associated on a workflow, denied read by regular, force grant by workflow, ask for read, should be denied'];

        // association on a workflow, write operation
        yield [StoredObjectRoleEnum::EDIT, true, true, true, null, WorkflowRelatedEntityPermissionHelper::FORCE_GRANT, 'associated on a workflow, write by regular, force grant by workflow, ask for write, should be granted'];
        yield [StoredObjectRoleEnum::EDIT, true, true, true, null, WorkflowRelatedEntityPermissionHelper::ABSTAIN, 'associated on a workflow, write by regular, abstain by workflow, ask for write, should be granted'];
        yield [StoredObjectRoleEnum::EDIT, false, true, true, null, WorkflowRelatedEntityPermissionHelper::FORCE_DENIED, 'associated on a workflow, write by regular, force grant by workflow, ask for write, should be denied'];
        yield [StoredObjectRoleEnum::EDIT, true, true, false, null, WorkflowRelatedEntityPermissionHelper::FORCE_GRANT, 'associated on a workflow, denied write by regular, force grant by workflow, ask for write, should be granted'];
        yield [StoredObjectRoleEnum::EDIT, false, true, false, null, WorkflowRelatedEntityPermissionHelper::ABSTAIN, 'associated on a workflow, denied write by regular, abstain by workflow, ask for write, should be granted'];
        yield [StoredObjectRoleEnum::EDIT, false, true, false, null, WorkflowRelatedEntityPermissionHelper::FORCE_DENIED, 'associated on a workflow, denied write by regular, force grant by workflow, ask for write, should be denied'];
    }
}

class DummyRepository implements AssociatedEntityToStoredObjectInterface
{
    public function __construct(private readonly ?object $relatedEntity) {}

    public function findAssociatedEntityToStoredObject(StoredObject $storedObject): ?object
    {
        return $this->relatedEntity;
    }
}
