<?php

declare(strict_types=1);

namespace App\Framework\Svg\ValueObjects\Transform;

use App\Framework\Exception\ErrorCode;
use App\Framework\Exception\FrameworkException;

/**
 * Value Object representing SVG scale transformation
 */
final readonly class Scale
{
    public function __construct(
        public float $x,
        public ?float $y = null
    ) {
        if ($x === 0.0) {
            throw FrameworkException::create(
                ErrorCode::VAL_INVALID_FORMAT,
                'Scale X cannot be zero'
            )->withData(['x' => $x]);
        }

        if ($y !== null && $y === 0.0) {
            throw FrameworkException::create(
                ErrorCode::VAL_INVALID_FORMAT,
                'Scale Y cannot be zero'
            )->withData(['y' => $y]);
        }
    }

    /**
     * Create uniform scale (same in X and Y)
     */
    public static function uniform(float $factor): self
    {
        return new self($factor, $factor);
    }

    /**
     * Convert to SVG transform function
     */
    public function toSvgString(): string
    {
        if ($this->y === null || $this->y === $this->x) {
            return sprintf('scale(%.2f)', $this->x);
        }

        return sprintf('scale(%.2f %.2f)', $this->x, $this->y);
    }

    /**
     * Check if scale is uniform
     */
    public function isUniform(): bool
    {
        return $this->y === null || $this->y === $this->x;
    }

    public function toArray(): array
    {
        return [
            'type' => 'scale',
            'x' => $this->x,
            'y' => $this->y ?? $this->x,
            'uniform' => $this->isUniform(),
        ];
    }
}
