<?php

namespace App\Modules\Inventory\Models;

use App\Modules\Admin\Tenancy\Traits\BelongsToTenant;
use App\Modules\Inventory\Support\InventoryLifecycleState;
use App\Modules\Inventory\Support\InventoryUserStamp;
use App\Modules\Inventory\Support\LogsInventoryCatalogActivity;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Item extends Model
{
    use BelongsToTenant;
    use InventoryUserStamp;
    use LogsInventoryCatalogActivity;

    protected $table = 'inventory_items';

    protected $fillable = [
        'tenant_id',
        'parent_item_id',
        'inventory_category_id',
        'default_unit_id',
        'sku',
        'barcode',
        'name',
        'description',
        'is_variant',
        'is_active',
        'lifecycle_state',
        'deactivated_at',
        'created_by',
        'updated_by',
    ];

    protected function casts(): array
    {
        return [
            'is_variant' => 'boolean',
            'is_active' => 'boolean',
            'lifecycle_state' => InventoryLifecycleState::class,
            'deactivated_at' => 'datetime',
        ];
    }

    public function parent(): BelongsTo
    {
        return $this->belongsTo(Item::class, 'parent_item_id');
    }

    public function variants(): HasMany
    {
        return $this->hasMany(Item::class, 'parent_item_id');
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(ItemCategory::class, 'inventory_category_id');
    }

    public function defaultUnit(): BelongsTo
    {
        return $this->belongsTo(InventoryUnit::class, 'default_unit_id');
    }

    public function attributeValues(): HasMany
    {
        return $this->hasMany(ItemAttributeValue::class, 'item_id');
    }

    public function prices(): HasMany
    {
        return $this->hasMany(ItemPrice::class, 'item_id');
    }
}
