<?php

namespace App\Models\Inventory;

use App\Models\Branch;
use App\Models\Catalog\Product;
use App\Models\Concerns\Auditable;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Concerns\BranchScoped;
use App\Models\Concerns\HasDefaultUnitFromProduct;
use App\Models\Lookups\AdjustmentReason;
use App\Models\Lookups\UnitOfMeasure;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class StockAdjustment extends Model
{
    use Auditable, BelongsToTenant, BranchScoped, HasDefaultUnitFromProduct, SoftDeletes;

    protected $fillable = [
        'branch_id', 'product_id', 'unit_id',
        'adjustment_reason_id', 'stock_batch_id',
        'before_stock', 'new_stock', 'diff', 'note', 'adjusted_by',
    ];

    protected function casts(): array
    {
        return [
            'before_stock' => 'decimal:4',
            'new_stock' => 'decimal:4',
            'diff' => 'decimal:4',
        ];
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class, 'branch_id');
    }

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

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

    public function reason(): BelongsTo
    {
        return $this->belongsTo(AdjustmentReason::class, 'adjustment_reason_id');
    }

    public function adjustedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'adjusted_by');
    }

    public function stockBatch(): BelongsTo
    {
        return $this->belongsTo(StockBatch::class, 'stock_batch_id');
    }
}
