<?php

declare(strict_types=1);

namespace App\Services;

final class ChartDataService
{
    /**
     * @param array<int, array<string, mixed>> $rows
     * @return array<string, mixed>
     */
    public function comparePayload(array $rows, string $title, $year, $compareYear): array
    {
        $labels = array_map(function (array $row): string {
            return (string) $row['month_name'];
        }, $rows);

        $currentValues = array_map(function (array $row): float {
            return (float) $row['current_value'];
        }, $rows);

        $compareValues = array_map(function (array $row): float {
            return (float) $row['compare_value'];
        }, $rows);

        return [
            'title' => $title,
            'labels' => $labels,
            'series' => [
                [
                    'label' => (string) $year,
                    'values' => $currentValues,
                ],
                [
                    'label' => (string) $compareYear,
                    'values' => $compareValues,
                ],
            ],
        ];
    }

    /** @param array<int, array<string, mixed>> $rows */
    public function total(array $rows, string $key): float
    {
        return array_sum(array_map(function (array $row) use ($key): float {
            return (float) $row[$key];
        }, $rows));
    }

    public function percentChange(float $current, float $compare): ?float
    {
        if (abs($compare) < 0.00001) {
            return null;
        }
        return (($current - $compare) / abs($compare)) * 100;
    }
}
