<?php

namespace App\Services;

use App\Enums\LocationState;
use App\Models\Notification;
use App\Repositories\DashboardUgelRepository;
use App\Repositories\StateRepository;

class DashboardUgelService
{

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

    public function __construct() {

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

    }

    public function getUgelProcessSummaryByGeneralState(int $period, ?int $groupId, ?int $subgroupId): array
    {
        return $this->processRepository->getUgelProcessSummaryByGeneralState($period, $groupId, $subgroupId);
    }

    public function getUgelProcessSummaryByPriority($period, ?int $groupId, ?int $subgroupId): array
    {
        $processes = $this->processService->getUnresolvedProcessesByPeriod($period);
        $states = $this->stateRepository->preloadStates();

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

        foreach ($processes as $process) {
            $lastLocation = $process->lastLocation();

            if (!$lastLocation) {
                continue;
            }

            if ((int)$lastLocation->group_id !== (int)$groupId) {
                continue;
            }
            if ($subgroupId !== null) {
                if ((int)$lastLocation->subgroup_id !== (int)$subgroupId) {
                    continue;
                }
            } else {
                if ($lastLocation->subgroup_id !== null) {
                    continue;
                }
            }

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

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

    public function getUrgentProcessesByGroupOrSubgroup(int $period, ?int $groupId, ?int $subgroupId, int $limit = 5): array
    {
        $processes = $this->processService->getUnresolvedProcessesByPeriod($period);
        $states = $this->stateRepository->preloadStates();
        $urgentes = [];

        foreach ($processes as $process) {
            $lastLocation = $process->lastLocation();
            if (!$lastLocation) {
                continue;
            }

            if ((int)$lastLocation->group_id !== (int)$groupId) {
                continue;
            }

            if ($subgroupId !== null) {
                if ((int)$lastLocation->subgroup_id !== (int)$subgroupId) {
                    continue;
                }
            } else {
                if ($lastLocation->subgroup_id !== null) {
                    continue;
                }
            }

            $state = $this->processService->getState($process, $states);

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

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

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

    public function getLastGroupOrSubgroupNotifications(int $groupId, ?int $subgroupId, int $limit = 3): array
    {
        $rows = $this->processRepository->getLastGroupOrSubgroupNotifications($groupId, $subgroupId, $limit);

        $notifications = [];
        foreach ($rows as $row) {
            $notifications[] = new Notification($row);
        }

        return $notifications;
    }

    public function getUgelProcessSummaryByLocationState($period, int $groupId, ?int $subgroupId): array
    {
        $results = $this->processRepository->getUgelProcessSummaryByLocationState($period, $groupId, $subgroupId);

        $summary = [];
        foreach (LocationState::getAll() as $state) {
            $summary[$state] = 0;
        }

        foreach ($results as $row) {
            $summary[$row['state']] = (int)$row['count'];
        }

        return $summary;
    }

    public function getLastDerivedProcesses($period, int $groupId, ?int $subgroupId, int $limit = 3): array
    {
        return $this->processRepository->getLastDerivedProcesses($period, $groupId, $subgroupId, $limit);
    }
}