<?php

namespace App\Models\Lookups;

use App\Models\Concerns\Auditable;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

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

    public const EACH = 'EACH';

    public const BOX = 'BOX';

    public const PAIR = 'PAIR';

    public const SET = 'SET';

    public const KG = 'KG';

    public const LTR = 'LTR';

    public const ML = 'ML';

    public const MTR = 'MTR';

    protected $fillable = ['uuid', 'code', 'name', 'is_fractional', 'sort_order', 'is_active'];

    protected function casts(): array
    {
        return [
            'is_fractional' => 'boolean',
            'is_active' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

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

    public static function findByCode(string $code): ?self
    {
        return static::query()->where('code', $code)->first();
    }

    public static function idOf(string $code): ?int
    {
        return static::findByCode($code)?->id;
    }
}
