<?php

namespace App\Services\Accounting;

use App\Enums\DocumentStatus;
use App\Models\CustomerInvoice;
use App\Models\VendorBill;
use App\Support\Decimal;

final class SettlementStatusService
{
    public function refreshCustomerInvoice(CustomerInvoice $invoice): void
    {
        $settled = Decimal::add($invoice->paid_total, $invoice->allocated_total);
        $remaining = Decimal::subtract($invoice->grand_total, $settled);

        $status = match (true) {
            Decimal::compare($remaining, '0') <= 0 => DocumentStatus::PAID,
            Decimal::compare($settled, '0') > 0 => DocumentStatus::PARTIALLY_PAID,
            default => DocumentStatus::POSTED,
        };

        $invoice->forceFill(['status' => $status])->save();
    }

    public function refreshVendorBill(VendorBill $bill): void
    {
        $settled = Decimal::add($bill->paid_total, $bill->allocated_total);
        $remaining = Decimal::subtract($bill->grand_total, $settled);

        $status = match (true) {
            Decimal::compare($remaining, '0') <= 0 => DocumentStatus::PAID,
            Decimal::compare($settled, '0') > 0 => DocumentStatus::PARTIALLY_PAID,
            default => DocumentStatus::POSTED,
        };

        $bill->forceFill(['status' => $status])->save();
    }
}
