<?php

namespace App\Models\Concerns;

use App\Models\Catalog\Product;

/**
 * Auto-fills unit_id from the linked product's base unit whenever a row is
 * saved without an explicit unit. The unit of measure is configured once on
 * the product (optionally templated from its sub-category); downstream
 * documents — GRNs, purchase orders, returns, damages, stock adjustments,
 * stock transfers, bundle items — then never ask the
 * user to pick a unit again, the product's own unit just follows along.
 */
trait HasDefaultUnitFromProduct
{
    protected static function bootHasDefaultUnitFromProduct(): void
    {
        static::saving(function (self $model): void {
            if (blank($model->unit_id) && filled($model->product_id)) {
                $model->unit_id = Product::query()->whereKey($model->product_id)->value('base_unit_id');
            }
        });
    }
}
