<?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\MainBundle\Security\Authorization;

use Chill\MainBundle\Entity\SavedExport;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Export\ExportManager;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

final class SavedExportVoter extends Voter
{
    final public const DELETE = 'CHILL_MAIN_EXPORT_SAVED_DELETE';

    final public const EDIT = 'CHILL_MAIN_EXPORT_SAVED_EDIT';

    final public const GENERATE = 'CHILL_MAIN_EXPORT_SAVED_GENERATE';

    final public const DUPLICATE = 'CHILL_MAIN_EXPORT_SAVED_DUPLICATE';

    final public const SHARE = 'CHILL_MAIN_EXPORT_SAVED_SHARE';

    private const ALL = [
        self::DELETE,
        self::EDIT,
        self::GENERATE,
        self::SHARE,
        self::DUPLICATE,
    ];

    public function __construct(
        private readonly ExportManager $exportManager,
        private readonly AccessDecisionManagerInterface $accessDecisionManager,
    ) {}

    protected function supports($attribute, $subject): bool
    {
        return $subject instanceof SavedExport && \in_array($attribute, self::ALL, true);
    }

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
    {
        /* @var SavedExport $subject */
        $user = $token->getUser();

        if (!$user instanceof User) {
            return false;
        }

        return match ($attribute) {
            self::DELETE, self::EDIT => $subject->getUser() === $token->getUser(),
            self::SHARE => $subject->getUser() === $token->getUser() && $this->accessDecisionManager->decide($token, [ChillExportVoter::COMPOSE_EXPORT]),
            self::DUPLICATE => $this->accessDecisionManager->decide($token, [ChillExportVoter::COMPOSE_EXPORT]) && $this->accessDecisionManager->decide($token, [self::EDIT], $subject) ,
            self::GENERATE => $this->canUserGenerate($user, $subject),
            default => throw new \UnexpectedValueException('attribute not supported: '.$attribute),
        };
    }

    private function canUserGenerate(User $user, SavedExport $savedExport): bool
    {
        if (!($savedExport->getUser() === $user || $savedExport->isSharedWithUser($user))) {
            return false;
        }

        $export = $this->exportManager->getExport($savedExport->getExportAlias());

        return $this->exportManager->isGrantedForElement($export);
    }
}
