<?php

declare(strict_types=1);

namespace App\Data\Images;

final readonly class CropBoxData
{
    public function __construct(
        public int $x,
        public int $y,
        public int $width,
        public int $height,
    ) {
    }

    public function clampToImage(int $imageWidth, int $imageHeight): self
    {
        $width = max(1, min($this->width, max(1, $imageWidth)));
        $height = max(1, min($this->height, max(1, $imageHeight)));

        $x = max(0, min($this->x, max(0, $imageWidth - $width)));
        $y = max(0, min($this->y, max(0, $imageHeight - $height)));

        return new self($x, $y, $width, $height);
    }

    public function centerX(): float
    {
        return $this->x + ($this->width / 2);
    }

    public function centerY(): float
    {
        return $this->y + ($this->height / 2);
    }

    /**
     * @return array{x: int, y: int, width: int, height: int}
     */
    public function toArray(): array
    {
        return [
            'x' => $this->x,
            'y' => $this->y,
            'width' => $this->width,
            'height' => $this->height,
        ];
    }
}