<?php

declare(strict_types=1);

namespace App\Application\LiveComponents\ValueObjects;

/**
 * ChartData - Value Object for chart data
 */
final readonly class ChartData
{
    public function __construct(
        public array $labels,
        public array $datasets,
        public ChartType $type
    ) {
    }

    public function addDataPoint(string $label, array $values): self
    {
        $newLabels = [...$this->labels, $label];
        $newDatasets = array_map(function ($dataset, $index) use ($values) {
            $datasetArray = (array) $dataset;
            $datasetArray['data'][] = $values[$index] ?? 0;

            return $datasetArray;
        }, $this->datasets, array_keys($this->datasets));

        return new self($newLabels, $newDatasets, $this->type);
    }

    public function trimToCount(int $maxCount): self
    {
        if (count($this->labels) <= $maxCount) {
            return $this;
        }

        $newLabels = array_slice($this->labels, -$maxCount);
        $newDatasets = array_map(function ($dataset) use ($maxCount) {
            $datasetArray = (array) $dataset;
            $datasetArray['data'] = array_slice($datasetArray['data'], -$maxCount);

            return $datasetArray;
        }, $this->datasets);

        return new self($newLabels, $newDatasets, $this->type);
    }

    public function getDataPointsCount(): int
    {
        return count($this->labels);
    }

    public function toArray(): array
    {
        return [
            'labels' => $this->labels,
            'datasets' => $this->datasets,
        ];
    }
}
