<?php

namespace App\Services\CompetitionScores;

use App\Models\CompetitionScore;

class CompetitionScoresSaveService
{
    public function filterScores(array $scores): array
    {
        $cleanScores = [];
        $invalidScores = [];

        foreach ($scores as $studentId => $scoreValue) {
            $scoreValue = trim((string) $scoreValue);
            if ($scoreValue === '') {
                continue;
            }
            if (!preg_match('/^\\d+$/', $scoreValue)) {
                $invalidScores[] = (int) $studentId;
                continue;
            }
            $cleanScores[(int) $studentId] = (int) $scoreValue;
        }

        return [$cleanScores, $invalidScores];
    }

    public function saveScores(int $competitionId, int $classSectionId, array $scores): void
    {
        foreach ($scores as $studentId => $scoreValue) {
            CompetitionScore::query()->updateOrCreate(
                [
                    'competition_id' => $competitionId,
                    'student_id' => (int) $studentId,
                    'class_section_id' => $classSectionId,
                ],
                [
                    'score' => (int) $scoreValue,
                    'class_section_id' => $classSectionId,
                ]
            );
        }
    }

    public function getScoreMap(int $competitionId, int $classSectionId): array
    {
        $rows = CompetitionScore::query()
            ->select('student_id', 'score')
            ->where('competition_id', $competitionId)
            ->where('class_section_id', $classSectionId)
            ->get()
            ->map(fn ($row) => $row->toArray())
            ->all();

        $map = [];
        foreach ($rows as $row) {
            $map[(int) $row['student_id']] = $row['score'];
        }

        return $map;
    }
}
