<?php

namespace App\Services;

use App\Models\Participant;

class ParticipantService
{
    protected static $prefixes = [
        'KBch0' => [
            'pria' => [
                1 => 'B',
                2 => 'D',
                5 => 'F',
            ],
            'wanita' => [
                1 => 'C',
                2 => 'E',
                5 => 'G',
            ],
        ]
    ];

    public static function generateSerialNumber(string $category, string $gender, int $runCategory): string
    {
        $prefix = self::$prefixes[$category][$gender][$runCategory] ?? null;
        
        if (!$prefix) {
            throw new \Exception("Kategori tidak ditemukan");
        }

        $latestParticipant = Peserta::where('package', $category)
                            ->where('jenis_kelamin', $gender)
                            ->where('category', $runCategory)
                            ->orderBy('bib_number', 'desc')
                            ->first();

        $nextNumber = $latestParticipant ? ((int)substr($latestParticipant->serial_number, 2) + 1) : 1;

        return sprintf("%s-%04d", $prefix, $nextNumber);
    }
}
