<?php

declare(strict_types=1);

namespace App\Application\Analytics\ValueObject;

use App\Framework\Core\ValueObjects\Percentage;

/**
 * Device usage breakdown for analytics reporting
 */
final readonly class DeviceBreakdown
{
    public function __construct(
        public int $desktop,
        public int $mobile,
        public int $tablet,
    ) {
        if ($desktop < 0 || $mobile < 0 || $tablet < 0) {
            throw new \InvalidArgumentException('Device counts cannot be negative');
        }
    }

    /**
     * Create from legacy array format: ['Desktop' => 60, 'Mobile' => 35, 'Tablet' => 5]
     * @param array<string, int> $data
     */
    public static function fromArray(array $data): self
    {
        return new self(
            desktop: $data['Desktop'] ?? 0,
            mobile: $data['Mobile'] ?? 0,
            tablet: $data['Tablet'] ?? 0,
        );
    }

    public function getTotal(): int
    {
        return $this->desktop + $this->mobile + $this->tablet;
    }

    public function getDesktopPercentage(): Percentage
    {
        return Percentage::fromRatio($this->desktop, $this->getTotal());
    }

    public function getMobilePercentage(): Percentage
    {
        return Percentage::fromRatio($this->mobile, $this->getTotal());
    }

    public function getTabletPercentage(): Percentage
    {
        return Percentage::fromRatio($this->tablet, $this->getTotal());
    }

    /**
     * @return array<string, int>
     */
    public function toArray(): array
    {
        return [
            'Desktop' => $this->desktop,
            'Mobile' => $this->mobile,
            'Tablet' => $this->tablet,
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public function toAnalyticsArray(): array
    {
        return [
            'Desktop' => $this->desktop,
            'Mobile' => $this->mobile,
            'Tablet' => $this->tablet,
            'desktop_percentage' => $this->getDesktopPercentage()->format(),
            'mobile_percentage' => $this->getMobilePercentage()->format(),
            'tablet_percentage' => $this->getTabletPercentage()->format(),
            'total' => $this->getTotal(),
        ];
    }
}
