<?php

namespace App\Modules\Sales\Services;

use App\Modules\Inventory\Stock\Support\DecimalQuantity;
use App\Modules\Sales\Models\SalesOrder;
use App\Modules\Sales\Models\SalesOrderLine;

final class SalesReturnFulfillmentAdjustmentService
{
    public function __construct(
        private readonly SalesOrderLifecycleWriter $statusWriter,
    ) {}

    public function reduceFulfilledQuantity(SalesOrderLine $line, string $quantity): void
    {
        $q = trim($quantity);
        $next = DecimalQuantity::add(trim((string) $line->quantity_fulfilled), DecimalQuantity::negate($q));
        $line->forceFill(['quantity_fulfilled' => $next])->save();
        $order = SalesOrder::withoutGlobalScopes()
            ->whereKey((int) $line->sales_order_id)
            ->lockForUpdate()
            ->first();
        if ($order !== null) {
            $this->statusWriter->persistAggregatedStatus($order);
        }
    }
}
