<?php

namespace App\Modules\Inventory\Stock\Services;

use App\Modules\Inventory\Stock\DTOs\ApplyMovementInput;
use App\Modules\Inventory\Stock\Exceptions\StockMovementValidationException;
use App\Modules\Inventory\Stock\Support\DecimalQuantity;
use App\Modules\Inventory\Stock\Support\InventoryStockMovementType;

final class SignedMovementQuantity
{
    public static function ledgerSignedQuantity(ApplyMovementInput $in): string
    {
        $q = trim($in->quantityInput);
        if ($in->type === InventoryStockMovementType::StockIn) {
            if (! DecimalQuantity::gtZero($q)) {
                throw new StockMovementValidationException('stock_in_quantity_positive');
            }

            return $q;
        }
        if ($in->type === InventoryStockMovementType::StockOut || $in->type === InventoryStockMovementType::TransferOut) {
            if (! DecimalQuantity::gtZero($q)) {
                throw new StockMovementValidationException('stock_out_quantity_positive');
            }

            return DecimalQuantity::negate($q);
        }

        if ($in->type === InventoryStockMovementType::TransferIn) {
            if (! DecimalQuantity::gtZero($q)) {
                throw new StockMovementValidationException('stock_in_quantity_positive');
            }

            return $q;
        }

        if (! DecimalQuantity::gtZero($q) && ! DecimalQuantity::isNegative($q)) {
            throw new StockMovementValidationException('adjustment_nonzero');
        }

        return $q;
    }
}
