<?php

declare(strict_types=1);

namespace App\Service;

use App\Entity\GameMode;
use App\Enum\GameModeType;
use App\Repository\GameModeRepository;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Doctrine\ORM\EntityManagerInterface;

readonly class GameModeBootstrapper
{
    public function __construct(
        private GameModeRepository     $gameModeRepository,
        private EntityManagerInterface $entityManager,
    ) {
    }

    public function ensureDefaults(): void
    {
        $defaultModes = [
            [
                'key' => 'x01_301',
                'name' => '301',
                'startScore' => 301,
                'type' => GameModeType::X01,
            ],
            [
                'key' => 'x01_501',
                'name' => '501',
                'startScore' => 501,
                'type' => GameModeType::X01,
            ],
            [
                'key' => 'around_the_world',
                'name' => 'Around the World',
                'startScore' => 1,
                'type' => GameModeType::ATW,
            ],
        ];

        $addedAny = false;

        foreach ($defaultModes as $modeConfig) {
            if ($this->gameModeRepository->findOneByKey($modeConfig['key']) instanceof GameMode) {
                continue;
            }

            $mode = new GameMode($modeConfig['key'], $modeConfig['name'], $modeConfig['startScore']);
            $mode->setType($modeConfig['type']);
            $this->entityManager->persist($mode);
            $addedAny = true;
        }

        if (!$addedAny) {
            return;
        }

        try {
            $this->entityManager->flush();
        } catch (UniqueConstraintViolationException $exception) {
            // Ignore
        }
    }
}
