<?php

declare(strict_types=1);

namespace App\Business\Inventory;

use App\Models\DberpInventoryBalance;
use Illuminate\Database\Eloquent\Builder;

final class InventoryWarningService
{
    public function __construct(
        private readonly InventoryRuleService $ruleService,
    ) {}

    public function query(): Builder
    {
        return DberpInventoryBalance::query()
            ->with(['product.category', 'warehouse'])
            ->where(function (Builder $query): void {
                $query->zeroStock();

                if ($this->ruleService->safetyStockAlertEnabled()) {
                    $query->orWhere(function (Builder $subQuery): void {
                        $subQuery->lowStock();
                    });
                }
            });
    }

    public function warningType(DberpInventoryBalance $balance): string
    {
        if ((float) $balance->realtime_quantity <= 0) {
            return 'zero_stock';
        }

        if (
            $this->ruleService->safetyStockAlertEnabled()
            && (float) $balance->safety_stock > 0
            && (float) $balance->available_quantity <= (float) $balance->safety_stock
        ) {
            return 'low_stock';
        }

        return 'normal';
    }

    public function warningTypeLabel(DberpInventoryBalance $balance): string
    {
        return __('dberp.options.inventory_warning_type.'.$this->warningType($balance));
    }
}