<?php declare(strict_types=1);

namespace App\Enums;

enum Permission: string
{
    case Role = 'role';
    case User = 'user';
    case CaptchaToken = 'captcha_token';

    public function getPermissions(): array
    {
        $permissions = match ($this) {
            self::CaptchaToken => [
                'view'   => __('permissions.Allowed to watch all tokens'),
                'view_own'   => __('permissions.Allowed to view own tokens'),
                'create' => __('permissions.Allowed to create tokens'),
                'update' => __('permissions.Allowed to edit all tokens'),
                'update_own' => __('permissions.Allowed to edit own tokens'),
                'delete' => __('permissions.Allowed to delete all tokens'),
                'delete_own' => __('permissions.Allowed to delete own tokens'),
            ],
            default => $this->getBasePermissions()
        };

        return $permissions;
    }

    public function getTitle(): string
    {
        return __('permissions.' . $this->name);
    }

    public function formatValue(string $permission): string
    {
        return $this->value . '.' . $permission;
    }

    public static function toArrayList(): array
    {
        $permissions = [];
        foreach (self::cases() as $permissionEnum) {
            foreach ($permissionEnum->getPermissions() as $permissionName => $permissionTitle) {
                $name = $permissionEnum->formatValue($permissionName);
                $title = $permissionEnum->getTitle() . ' - ' . $permissionTitle;
                $permissions[$name] = $title;
            }
        }

        return $permissions;
    }

    public static function toArrayListCodes(): array
    {
        return \array_keys(self::toArrayList());
    }

    private function getBasePermissions(): array
    {
        return [
            'view'   => __('permissions.Allowed to watch'),
            'create' => __('permissions.Allowed to create'),
            'update' => __('permissions.Allowed to edit'),
            'delete' => __('permissions.Allowed to delete'),
        ];
    }
}
