<?php

namespace App\Dto\Output;

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\Get;
use App\Entity\OrganizationalUnit;
use App\Entity\User;
use App\Entity\UserGroup;
use Symfony\Component\Serializer\Annotation\Groups;

#[Get(shortName: 'User')]
final class UserOutput extends AbstractOutput
{
    #[Groups(['user:read'])]
    #[ApiProperty(
        description: 'El nombre de usuario',
        example: 'admin'
    )]
    public string $username;

    #[Groups(['user:read'])]
    #[ApiProperty(
        description: 'Los roles asignados al usuario',
        example: ['ROLE_USER', 'ROLE_ADMIN']
    )]
    public array $roles;

    #[Groups(['user:read'])]
    #[ApiProperty(
        description: 'Indica si el usuario está habilitado',
        example: true
    )]
    public bool $enabled;

    #[Groups(['user:read'])]
    #[ApiProperty(
        description: 'Las unidades organizativas permitidas para el usuario',
        example: []
    )]
    public array $allowedOrganizationalUnits;

    #[Groups(['user:read'])]
    #[ApiProperty(
        description: 'Los grupos de usuario asignados',
        example: []
    )]
    public array $userGroups;

    #[Groups(['user:read'])]
    #[ApiProperty(
        description: 'La vista por defecto de grupos para el usuario',
        example: 'card'
    )]
    public ?string $groupsView = 'card';

    #[Groups(['user:read'])]
    #[ApiProperty(
        description: 'Fecha de creación del usuario',
        example: '2024-01-15T10:30:00+00:00'
    )]
    public \DateTime $createdAt;

    #[Groups(['user:read'])]
    #[ApiProperty(
        description: 'Usuario que creó este registro',
        example: 'admin'
    )]
    public ?string $createdBy = null;

    public function __construct(User $user)
    {
        parent::__construct($user);

        $this->username = $user->getUsername();
        $this->roles = $user->getRoles();
        $this->enabled = $user->isEnabled();
        $this->groupsView = $user->getGroupsView();

        $this->userGroups = $user->getUserGroups()->map(
            fn(UserGroup $userGroup) => new UserGroupOutput($userGroup)
        )->toArray();

        $this->allowedOrganizationalUnits = $user->getAllowedOrganizationalUnits()->map(
            fn(OrganizationalUnit $organizationalUnit) => new OrganizationalUnitOutput($organizationalUnit)
        )->toArray();

        $this->createdAt = $user->getCreatedAt();
        $this->createdBy = $user->getCreatedBy();
    }
}