<?php

declare(strict_types=1);

namespace App\Application\LiveComponents\ImageUploader;

use App\Application\LiveComponents\LiveComponentState;

/**
 * Type-safe state for ImageUploaderComponent
 *
 * Provides compile-time type safety for image uploader state.
 * All properties are readonly and immutable - transformations return new instances.
 */
final readonly class ImageUploaderState implements LiveComponentState
{
    public function __construct(
        public ?string $uploadedImage = null,
        public ?string $imageUrl = null,
        public int $uploadCount = 0
    ) {
    }

    /**
     * Create from array (LiveComponentState interface)
     */
    public static function fromArray(array $data): self
    {
        return new self(
            uploadedImage: $data['uploaded_image'] ?? null,
            imageUrl: $data['image_url'] ?? null,
            uploadCount: (int) ($data['upload_count'] ?? 0)
        );
    }

    /**
     * Create empty state with defaults
     */
    public static function empty(): self
    {
        return new self();
    }

    /**
     * Convert to array (LiveComponentState interface)
     */
    public function toArray(): array
    {
        return [
            'uploaded_image' => $this->uploadedImage,
            'image_url' => $this->imageUrl,
            'upload_count' => $this->uploadCount,
        ];
    }

    /**
     * Update with uploaded image
     */
    public function withUploadedImage(string $filename, string $imageUrl): self
    {
        return new self(
            uploadedImage: $filename,
            imageUrl: $imageUrl,
            uploadCount: $this->uploadCount + 1
        );
    }

    /**
     * Clear uploaded image
     */
    public function clear(): self
    {
        return new self(
            uploadedImage: null,
            imageUrl: null,
            uploadCount: $this->uploadCount
        );
    }

    /**
     * Check if an image is uploaded
     */
    public function hasImage(): bool
    {
        return $this->uploadedImage !== null && $this->imageUrl !== null;
    }

    /**
     * Get upload count
     */
    public function getUploadCount(): int
    {
        return $this->uploadCount;
    }

    /**
     * Reset upload count
     */
    public function resetUploadCount(): self
    {
        return new self(
            uploadedImage: $this->uploadedImage,
            imageUrl: $this->imageUrl,
            uploadCount: 0
        );
    }
}
