<?php

namespace App\Console\Commands;

use App\Services\BranchContext;
use App\Services\OverdueLoanService;
use Illuminate\Console\Command;

class UpdateLoanArrears extends Command
{
    protected $signature = 'loans:update-overdue {--date= : Process arrears as of a specific YYYY-MM-DD date}';
    protected $description = 'Update overdue loan buckets and assess any due late-payment penalties';

    public function handle(OverdueLoanService $service, BranchContext $context): int
    {
        return $context->systemWide(function () use ($service): int {
            $date = $this->option('date') ?: today()->toDateString();
            $stats = $service->process((string) $date);
            $this->info(sprintf(
                'Processed %d active loans; %d overdue; penalties added %s.',
                $stats['processed'], $stats['overdue'], $stats['penalties_added']
            ));
            return self::SUCCESS;
        });
    }
}
