<?php

declare(strict_types=1);

namespace Tvdt\Factory;

use Doctrine\ORM\EntityManagerInterface;
use Tvdt\Entity\Elimination;
use Tvdt\Entity\Quiz;
use Tvdt\Repository\QuizRepository;

final readonly class EliminationFactory
{
    public function __construct(
        private QuizRepository $quizRepository,
        private EntityManagerInterface $em,
    ) {}

    public function createEliminationFromQuiz(Quiz $quiz): Elimination
    {
        $elimination = new Elimination($quiz);
        $this->em->persist($elimination);

        $scores = $this->quizRepository->getScores($quiz);

        $simpleScores = [];

        foreach (array_reverse($scores) as $i => $score) {
            $simpleScores[$score->name] = $i < $quiz->dropouts ? Elimination::SCREEN_RED : Elimination::SCREEN_GREEN;
        }

        $elimination->data = $simpleScores;

        $this->em->flush();

        return $elimination;
    }
}
