<?php

namespace App\Models\Catalog;

use App\Models\Concerns\Auditable;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Lookups\UnitOfMeasure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class ProductUnit extends Model
{
    use Auditable, BelongsToTenant, SoftDeletes;

    protected $fillable = [
        'uuid', 'product_id', 'unit_id',
        'conversion_factor', 'sale_price', 'barcode', 'is_default_sale_unit',
    ];

    protected function casts(): array
    {
        return [
            'conversion_factor' => 'decimal:4',
            'sale_price' => 'decimal:2',
            'is_default_sale_unit' => 'boolean',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (self $productUnit): void {
            if (! $productUnit->uuid) {
                $productUnit->uuid = (string) Str::ulid();
            }
        });
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    public function unit(): BelongsTo
    {
        return $this->belongsTo(UnitOfMeasure::class, 'unit_id');
    }
}
