<?php

namespace App\Services\CompetitionScores;

use App\Models\ClassSection;
use App\Models\Configuration;
use App\Models\TeacherClass;

class CompetitionScoresContextService
{
    public function getTeacherContext(int $userId): array
    {
        $schoolYear = (string) (Configuration::getConfig('school_year') ?? '');
        $semester = (string) (Configuration::getConfig('semester') ?? '');
        $assignments = TeacherClass::getClassAssignmentsByUserId($userId, $schoolYear, $semester);

        return [$assignments, $schoolYear, $semester];
    }

    public function getAllowedClassIds(array $assignments): array
    {
        $ids = array_map(static function ($row) {
            return (int) ($row['class_section_id'] ?? 0);
        }, $assignments);

        return array_values(array_filter(array_unique($ids)));
    }

    public function resolveActiveClassId(array $assignments, int $requestedClassId = 0): int
    {
        $allowed = $this->getAllowedClassIds($assignments);
        if ($requestedClassId > 0 && in_array($requestedClassId, $allowed, true)) {
            return $requestedClassId;
        }

        return (int) ($allowed[0] ?? 0);
    }

    public function getActiveClassName(array $assignments, int $classSectionId): ?string
    {
        if ($classSectionId <= 0) {
            return null;
        }

        foreach ($assignments as $row) {
            if ((int) ($row['class_section_id'] ?? 0) === $classSectionId) {
                return $row['class_section_name'] ?? null;
            }
        }

        return ClassSection::getClassSectionNameBySectionId($classSectionId);
    }

    public function getClassSectionMap(): array
    {
        $sections = ClassSection::query()
            ->select('class_section_id', 'class_section_name')
            ->orderBy('class_section_name', 'ASC')
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();

        $map = [];
        foreach ($sections as $section) {
            $id = (int) ($section['class_section_id'] ?? 0);
            if ($id > 0) {
                $map[$id] = $section['class_section_name'] ?? (string) $id;
            }
        }

        return $map;
    }
}
