<?php

namespace App\Casts;

use Hyperf\Contract\CastsAttributes;
use App\Enums\UserActions;

class UserActionsArrayCast implements CastsAttributes
{
    public function get($model, string $key, $value, array $attributes)
    {
        if (empty($value)) {
            return [];
        }

        $roles = json_decode($value, true) ?? [];

        return array_filter(array_map(
            fn ($role) => UserActions::tryFrom($role),
            $roles
        ));
    }

    public function set($model, string $key, $value, array $attributes)
    {
        if ($value === null) {
            return null;
        }

        // Ensure only backing values get saved
        $roles = array_map(
            fn ($role) => $role instanceof UserActions ? $role->value : UserActions::from($role)->value,
            $value
        );

        return json_encode($roles);
    }
}