<?php

namespace App\Services\Incidents;

use App\Models\Incident;

class IncidentHistoryService
{
    public function __construct(private IncidentLookupService $lookup)
    {
    }

    public function history(?string $schoolYear, ?string $semester): array
    {
        $builder = Incident::query()->orderBy('incident_datetime', 'DESC');
        if ($schoolYear !== null && $schoolYear !== '') {
            $builder->where('school_year', $schoolYear);
        }
        if ($semester !== null && $semester !== '') {
            $builder->where('semester', $semester);
        }

        return $builder->get()->map(fn ($row) => $row->toArray())->all();
    }

    public function processed(?string $schoolYear, ?string $semester): array
    {
        $incidents = $this->history($schoolYear, $semester);
        if (empty($incidents)) {
            return [];
        }

        $gradeMap = $this->lookup->gradeNameMap(array_column($incidents, 'grade'));

        $updaterIds = [];
        foreach ($incidents as $incident) {
            foreach (['updated_by_open', 'updated_by_closed', 'updated_by_canceled'] as $key) {
                if (!empty($incident[$key])) {
                    $updaterIds[] = (int) $incident[$key];
                }
            }
        }

        $updaterMap = $this->lookup->updaterNameMap($updaterIds);

        foreach ($incidents as &$incident) {
            foreach (['updated_by_open', 'updated_by_closed', 'updated_by_canceled'] as $key) {
                $id = (int) ($incident[$key] ?? 0);
                $incident[$key . '_name'] = $id > 0 ? ($updaterMap[$id] ?? null) : null;
            }

            $gradeValue = $incident['grade'] ?? '';
            if (is_numeric($gradeValue)) {
                $incident['grade'] = $gradeMap[(int) $gradeValue] ?? (string) $gradeValue;
            }
        }
        unset($incident);

        return $incidents;
    }
}
