<?php

namespace App\Security\Voter;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Entity\User;
use App\RecordStatus;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManager;

final class RecordVoter extends Voter
{
    public const EDIT = 'RECORD_EDIT';
    public const DELETE = 'RECORD_DELETE';
    public const COPY = 'RECORD_COPY';
    public const VIEW = 'RECORD_VIEW';

    protected function supports(string $attribute, mixed $subject): bool
    {
        return in_array($attribute, [self::EDIT, self::VIEW, self::DELETE, self::COPY])
            && $subject instanceof \App\RecordInterface;
    }

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();

        // if the user is anonymous, do not grant access
        if (!$user instanceof UserInterface) {
            return false;
        }

        $roles = $user->getRoles();

        // TODO: Better way to check roles?
        switch ($attribute) {
            case self::EDIT:
                $editorAllowed = true;
                if (in_array('ROLE_EDITOR', $roles)) {
                    $creator = $subject->getCreator();
                    $isCreator = $creator === $user->getUsername();
                    $creatorIsEditor = $subject->getEditableStatus();

                    $editorAllowed &= $isCreator || $creatorIsEditor;
                }

                return in_array('ROLE_ADMIN', $roles)
                       || in_array('ROLE_REVISOR', $roles)
                       || $editorAllowed;
            case self::DELETE:
                $editorAllowed = true;
                if (in_array('ROLE_EDITOR', $roles)) {
                    $isCreator = $subject->getCreator() === $user->getUsername();
                    $isValidStatus = match($subject->getStatus()) {
                        RecordStatus::Draft => true,
                        RecordStatus::Complete => true,
                        default => false
                    };

                    $editorAllowed &= $isCreator && $isValidStatus;
                }

                return in_array('ROLE_ADMIN', $roles)
                       || in_array('ROLE_REVISOR', $roles)
                       || $editorAllowed;
                break;

            case self::COPY:
            case self::VIEW:
                return  ! in_array('ROLE_READER', $roles);
                break;
        }

        return false;
    }
}

