<?php

namespace App\Filament\Resources\Concerns;

use App\Exceptions\InsufficientStockException;
use App\Models\Branch;
use App\Models\Catalog\Product;
use App\Support\Quantity;
use Illuminate\Validation\ValidationException;

/**
 * Turns a stock shortfall into an ordinary form error.
 *
 * {@see InsufficientStockException} carries a render() that answers with a 422
 * JSON body. That is the right shape for an API caller, but a Filament create
 * page is not one — letting the exception escape put a raw payload on screen
 * where a field error belonged. Pages that move stock out of a branch catch it
 * and rethrow through here instead.
 *
 * The message is rebuilt rather than reused: the exception names the product
 * and branch by id, which means nothing on a form that only ever showed their
 * names.
 */
trait ReportsStockShortfall
{
    /**
     * @param  string  $field  the form field to report against — whichever one
     *                         the user can actually change to resolve it
     */
    protected static function stockShortfall(InsufficientStockException $e, string $field): ValidationException
    {
        $product = Product::find($e->productId);
        $unit = $product?->baseUnit;

        return ValidationException::withMessages([
            $field => sprintf(
                '%s has only %s at %s, but this needs %s.',
                $product?->name ?? 'This product',
                Quantity::format($e->available, $unit),
                Branch::find($e->branchId)?->name ?? 'that branch',
                Quantity::format($e->requested, $unit),
            ),
        ]);
    }
}
