<?php

declare(strict_types=1);

namespace App\Application\User;

use App\Framework\Core\ValueObjects\EmailAddress;
use App\Framework\Exception\ErrorCode;
use App\Framework\Exception\FrameworkException;

/**
 * User Data Value Object
 * Framework-konformes Value Object statt primitive Arrays
 */
final readonly class UserData
{
    public function __construct(
        public int $id,
        public EmailAddress $email,
        public string $name,
        public bool $active = true
    ) {
        if (trim($name) === '') {
            throw FrameworkException::create(
                ErrorCode::VAL_BUSINESS_RULE_VIOLATION,
                'User name cannot be empty'
            )->withData(['name' => $name]);
        }
    }

    /**
     * Konvertiert zu Array für GraphQL/API Kompatibilität
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'email' => $this->email->toString(),
            'name' => $this->name,
            'active' => $this->active,
        ];
    }

    /**
     * Factory Method für Array-Input (Migration von primitives)
     * @param array<string, mixed> $data
     */
    public static function fromArray(array $data): self
    {
        return new self(
            id: $data['id'] ?? 0,
            email: new EmailAddress($data['email'] ?? ''),
            name: $data['name'] ?? '',
            active: $data['active'] ?? true
        );
    }

    public function isActive(): bool
    {
        return $this->active;
    }

    public function getDisplayName(): string
    {
        return $this->name;
    }

    public function getMaskedEmail(): string
    {
        return $this->email->obfuscate();
    }
}
