<?php

namespace App\Services;

use App\Repositories\DashboardAdminRepository;
use App\Repositories\StateRepository;

class DashboardAdminService
{

    protected ProcessService $processService;
    protected DashboardAdminRepository $processRepository;
    protected StateRepository $stateRepository;

    public function __construct() {

        $this->processService = new ProcessService();
        $this->processRepository = new DashboardAdminRepository();
        $this->stateRepository = new StateRepository();
    }

    public function getAdminProcessSummaryByGeneralState($period): array
    {
        return $this->processRepository->getAdminProcessSummaryByGeneralState($period);
    }

    public function getProcessCountsByAreaAndGeneralState($period): array
    {
        return $this->processRepository->getProcessCountsByAreaAndGeneralState($period);
    }

    public function getGlobalProcessStatesByPeriod($period): array
    {
        $processes = $this->processService->getUnresolvedProcessesByPeriod($period);
        $states = $this->stateRepository->preloadStates();

        $conteo = [
            'NORMAL' => 0,
            'ADVERTENCIA' => 0,
            'URGENTE' => 0,
        ];

        foreach ($processes as $process) {
            $state = $this->processService->getState($process, $states);
            if ($state) {
                $conteo[$state->description]++;
            }
        }

        return [
            ['priority' => 'NORMAL', 'count' => $conteo['NORMAL']],
            ['priority' => 'ADVERTENCIA', 'count' => $conteo['ADVERTENCIA']],
            ['priority' => 'URGENTE', 'count' => $conteo['URGENTE']],
        ];
    }

    public function getUrgentProcesses($period, int $limit = 5): array
    {
        $processes = $this->processService->getUnresolvedProcessesByPeriod($period);
        $states = $this->stateRepository->preloadStates();

        $urgentes = [];

        foreach ($processes as $process) {
            $state = $this->processService->getState($process, $states);

            if ($state && $state->description === 'URGENTE') {
                $urgentes[] = $process;
            }
        }

        usort($urgentes, function ($a, $b) {
            $aPorcentaje = $this->processService->getElapsedPercentage($a);
            $bPorcentaje = $this->processService->getElapsedPercentage($b);
            return $bPorcentaje <=> $aPorcentaje;
        });

        return array_slice($urgentes, 0, $limit);
    }

    public function getCurrentProcessStatesByArea($period): array
    {
        return $this->processRepository->getCurrentProcessStatesByArea($period);
    }

}