<?php

namespace App\Services\Reports;

use App\Repositories\Reports\AverageTimeInBrandNewRepository;

class AverageTimeInBrandNewService
{

    /**
     * Constructor for the class that initializes the repository dependency.
     *
     * @param AverageTimeInBrandNewRepository $repository The repository instance for managing average time data.
     */
    public function __construct(protected AverageTimeInBrandNewRepository $repository)
    {
    }

    /**
     * Retrieves and formats the average time data for brand new items assigned within a specific year.
     *
     * @param int $year The year for which the average time data is being retrieved.
     *
     * @return array The formatted average time data for each month of the specified year.
     */
    public function averageTimeInBrandNewData($year)
    {
        $resultData = $this->repository->getMonthlyAvgTimeFromBrandNewToAssignedInYear($year);

        return $this->formatAverageTimeInBrandNewDataWithMonth($resultData, $year);
    }

    /**
     * Set zero to non existing months data and find avg time of a assets get assigned from brand new
     *
     * @param array $averageTimeInBrandNewData The raw average time data for brand new items, where each item
     * includes a 'yearMonth' (YYYY-MM) and 'avg_time'.
     *
     * @param int   $year                      The year for which the data is being formatted.
     *
     * @return array An associative array containing:
     *  - 'months': A list of month names.
     *  - 'avg_time': The formatted average time data with each month represented, even if no data was present.
     */
    public function formatAverageTimeInBrandNewDataWithMonth($averageTimeInBrandNewData, $year)
    {
        $avgTimes = $averageTimeInBrandNewData;
        $months = [1 => "January", 2 => "February", 3 => "March", 4 => "April", 5 => "May", 6 => "June", 7 => "July", 8 => "August", 9 => "September", 10 => "October", 11 => "November", 12 => "Dec"];

        foreach (array_keys($months) as $month) {
            if (!array_key_exists($month, array_column($averageTimeInBrandNewData, 'yearMonth', 'month'))) {
                array_push($avgTimes, array(
                    'yearMonth' => $year . '-' . $month,
                    'month' => $month,
                    'avg_time' => 0
                ));
            }
        }

        return array(
            'months' => array_values($months),
            'avg_time' => $avgTimes
        );
    }
}
