<?php

namespace App\Models\Ecommerce\Product\Inventory;

use App\Models\Ecommerce\Channel\Channel;
use App\Models\Ecommerce\Product\Product\Product;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;

class Inventory extends Model
{
    use HasFactory;
    use HasSlug;

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'name',
        'code',
        'description',
        'email',
        'phone_number',
        'street_address',
        'zipcode',
        'region',
        'province_id',
        'longitude',
        'latitude',
        'is_default',
        'channel_id',
        'shareable',
    ];

    /**
     * Get the options for generating the slug.
     */
    public function getSlugOptions(): SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('name')
            ->saveSlugsTo('code')
            ->doNotGenerateSlugsOnUpdate();
    }

    /**
     * User Channel
     */
    public function channel(): BelongsTo
    {
        return $this->belongsTo(Channel::class);
    }

    /**
     * Products
     */
    public function products()
    {
        return $this->belongsToMany(Product::class)->withPivot('stock');
    }

    /**
     * Tmpost default inventory
     */
    public static function tmpostDefault(): Inventory
    {
        return static::where('code', 'tmpost')->first();
    }

    /**
     * History
     */
    public function history(): HasMany
    {
        return $this->hasMany(InventoryHistory::class, 'inventory_id');
    }

    /**
     * History removed
     */
    public function historyRemoved(): HasMany
    {
        return $this->hasMany(InventoryHistoryRemoved::class, 'inventory_id');
    }
}
