<?php

namespace App\Dto\Input;

use ApiPlatform\Metadata\ApiProperty;
use App\Entity\UserGroup;
use App\Validator\Constraints\UserGroupsValidPermission;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;

final class UserGroupInput
{
    #[Assert\NotBlank]
    #[Groups(['user-group:write'])]
    #[ApiProperty(
        description: 'El nombre del grupo de usuario',
        example: 'Administradores'
    )]
    public ?string $name = null;

    #[Groups(['user-group:write'])]
    #[UserGroupsValidPermission]
    #[ApiProperty(
        description: 'Los permisos del grupo de usuario',
        example: ['ROLE_ADMIN', 'ROLE_USER_MANAGEMENT']
    )]
    public ?array $permissions = [];

    #[Assert\NotNull]
    #[Groups(['user-group:write'])]
    #[ApiProperty(
        description: 'Si el grupo está habilitado',
        example: true
    )]
    public ?bool $enabled = false;

    public function __construct(?UserGroup $userGroupGroup = null)
    {
        if (!$userGroupGroup) {
            return;
        }

        $this->name = $userGroupGroup->getName();
        $this->permissions = $userGroupGroup->getPermissions();
        $this->enabled= $userGroupGroup->isEnabled();
    }

    public function createOrUpdateEntity(?UserGroup $userGroup = null): UserGroup
    {
        if (!$userGroup) {
            $userGroup = new UserGroup();
        }

        $userGroup->setName($this->name);
        $userGroup->setPermissions($this->permissions);
        $userGroup->setEnabled($this->enabled);
        
        return $userGroup;
    }
}