<?php

namespace App\Support;

use Carbon\Carbon;

final class DebtDueDate
{
    /**
     * Next calendar payment day (start of day) for sorting: ascending = soonest first.
     *
     * @param  array<string, mixed>  $debt
     */
    public static function nextOccurrenceTimestamp(array $debt): int
    {
        $today = Carbon::now()->startOfDay();
        $day = max(1, min(31, (int) ($debt['dueDay'] ?? 1)));
        $daysThisMonth = $today->daysInMonth;
        $dueThisMonth = $today->copy()->day(min($day, $daysThisMonth))->startOfDay();
        $nextMonthAnchor = $today->copy()->addMonthNoOverflow()->startOfMonth();
        $daysNextMonth = $nextMonthAnchor->daysInMonth;
        $dueNextMonth = $nextMonthAnchor->copy()->day(min($day, $daysNextMonth))->startOfDay();

        $next = $dueThisMonth->gte($today) ? $dueThisMonth : $dueNextMonth;

        return (int) $next->timestamp;
    }
}
