<?php

declare(strict_types=1);

namespace App\Application\LiveComponents\DTOs;

/**
 * Update Profile Request DTO
 *
 * Example DTO for testing parameter binding with constructor promotion.
 * Demonstrates automatic instantiation from action parameters.
 *
 * Usage in LiveComponent action:
 * ```php
 * #[Action]
 * public function updateProfile(UpdateProfileRequest $request): ComponentData
 * {
 *     // $request is automatically instantiated from action parameters
 *     $this->name = $request->name;
 *     $this->email = $request->email;
 *
 *     return $this->getData();
 * }
 * ```
 */
final readonly class UpdateProfileRequest
{
    public function __construct(
        public string $name,
        public string $email,
        public ?string $bio = null,
        public ?string $website = null
    ) {
        $this->validate();
    }

    /**
     * Validate DTO data
     */
    private function validate(): void
    {
        if (empty(trim($this->name))) {
            throw new \InvalidArgumentException('Name cannot be empty');
        }

        if (! filter_var($this->email, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('Invalid email address');
        }

        if ($this->website !== null && ! filter_var($this->website, FILTER_VALIDATE_URL)) {
            throw new \InvalidArgumentException('Invalid website URL');
        }

        if ($this->bio !== null && strlen($this->bio) > 500) {
            throw new \InvalidArgumentException('Bio cannot exceed 500 characters');
        }
    }

    /**
     * Convert to array for storage
     */
    public function toArray(): array
    {
        return [
            'name' => $this->name,
            'email' => $this->email,
            'bio' => $this->bio,
            'website' => $this->website,
        ];
    }
}
