<?php

namespace App\Services\Fees;

class FeeGradeService
{
    public function normalizeGrade(?string $grade): string
    {
        $normalized = strtoupper(trim((string) $grade));
        return str_replace([' ', '-'], '', $normalized);
    }

    public function compareGrades(string $gradeA, string $gradeB): int
    {
        $normA = $this->normalizeGrade($gradeA);
        $normB = $this->normalizeGrade($gradeB);

        $valA = $this->getGradeLevel($normA);
        $valB = $this->getGradeLevel($normB);

        if ($valA !== $valB) {
            return $valA <=> $valB;
        }

        preg_match('/\d+([A-Z]*)$/i', $normA, $suffixA);
        preg_match('/\d+([A-Z]*)$/i', $normB, $suffixB);

        return strcmp($suffixA[1] ?? '', $suffixB[1] ?? '');
    }

    public function getGradeLevel(string $grade): int
    {
        $grade = $this->normalizeGrade($grade);

        if ($grade === 'K') {
            return 0;
        }
        if ($grade === 'Y') {
            return 99;
        }

        if (preg_match('/^(\d+)/', $grade, $matches)) {
            return (int) $matches[1];
        }

        return 999;
    }
}
