<?php

namespace Database\Seeders;

use App\Models\Level;
use Illuminate\Database\Seeder;

class LevelSeeder extends Seeder
{
    public function run(): void
    {
        $tiers = [
            'Bronze',
            'Argent',
            'Or',
            'Platine',
            'Diamant',
            'Maître',
            'Grand Maître',
            'Légende',
        ];

        $levelsPerTier = 10;
        $baseXp = 50;
        $scalingFactor = 20;
        $totalLevels = count($tiers) * $levelsPerTier;

        for ($level = 1; $level <= $totalLevels; $level++) {

            // Déterminer le tier
            $tierIndex = intdiv($level - 1, $levelsPerTier);
            $tierName = $tiers[$tierIndex] ?? 'Légende';

            // Rang dans le tier (I, II, III…)
            $rankInTier = (($level - 1) % $levelsPerTier) + 1;
            $romanRank = $this->toRoman($rankInTier);

            // XP non linéaire
            $xpThreshold = $baseXp + ($level * $level * $scalingFactor);

            Level::updateOrCreate(
                ['level_position' => $level],
                [
                    'xpThreshold' => $xpThreshold,
                    'label' => "{$tierName} {$romanRank}",
                ]
            );
        }
    }

    private function toRoman(int $number): string
    {
        $map = [
            'X' => 10,
            'IX' => 9,
            'V' => 5,
            'IV' => 4,
            'I' => 1,
        ];

        $result = '';
        foreach ($map as $roman => $value) {
            while ($number >= $value) {
                $result .= $roman;
                $number -= $value;
            }
        }

        return $result;
    }
}
