<?php

declare(strict_types=1);

namespace App\Service\Finance;

use App\Entity\AnneeScolaire;
use App\Entity\Ecole;
use App\Repository\PaiementRepository;

final class RecuNumberGenerator
{
    public function __construct(private readonly PaiementRepository $paiementRepository)
    {
    }

    public function generate(Ecole $ecole, ?AnneeScolaire $annee = null): string
    {
        $year = $annee?->getDateDebut()?->format('y') ?: (new \DateTimeImmutable())->format('y');
        $prefix = $ecole->getPrefixeMatricule() ?: 'MAD';
        $base = sprintf('REC-%s-%s-', $year, mb_strtoupper($prefix));
        $last = $this->paiementRepository->findLastReceiptNumberWithPrefix($base);
        $next = 1;

        if ($last && preg_match('/(\d+)$/', $last, $matches) === 1) {
            $next = ((int) $matches[1]) + 1;
        }

        return $base.str_pad((string) $next, 4, '0', STR_PAD_LEFT);
    }
}
