<?php

namespace App\Services;

use App\Models\CustomerStatementEntry;
use App\Models\Loan;

class CustomerStatementBalanceService
{
    public function __construct(private MoneyMath $money) {}

    public function recalculate(Loan $loan): void
    {
        $balance = 0;
        $entries = CustomerStatementEntry::query()
            ->where('loan_id', $loan->id)
            ->orderBy('entry_date')
            ->orderBy('id')
            ->get();

        foreach ($entries as $entry) {
            $balance += $this->money->toMinor((string) $entry->debit);
            $balance -= $this->money->toMinor((string) $entry->credit);
            $entry->update(['running_balance' => $this->money->fromMinor(max(0, $balance))]);
        }
    }
}
