<?php

namespace App\Modules\Sales\Repositories;

use App\Modules\Sales\Models\SalesReturnLine;
use App\Modules\Sales\Support\SalesReturnStatus;
class SalesReturnLineQuantityRepository
{
    /**
     * Sum quantities already processed for this order line (other returns).
     */
    public function sumProcessedQuantityForOrderLine(
        int $tenantId,
        int $salesOrderLineId,
        ?int $excludeReturnId = null,
    ): string {
        $q = SalesReturnLine::withoutGlobalScopes()
            ->where('tenant_id', $tenantId)
            ->where('sales_order_line_id', $salesOrderLineId)
            ->whereHas('salesReturn', static function ($r) use ($excludeReturnId): void {
                $r->where('status', SalesReturnStatus::Processed->value);
                if ($excludeReturnId !== null) {
                    $r->where('id', '!=', $excludeReturnId);
                }
            });

        $v = $q->sum('quantity');

        return trim((string) ($v ?? '0'));
    }
}
