<?php

namespace App\Models\Tenant;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;

/**
 * Immutable ledger of every stock movement. The qty/cost reality of the
 * warehouse can always be reconstructed by aggregating these events.
 */
class WarehouseEvent extends Model
{
    use BelongsToTenant;

    public const TYPES = [
        'opening' => 'Stoc inițial',
        'receipt' => 'Recepție',
        'issue' => 'Consum',
        'transfer_out' => 'Transfer (ieșire)',
        'transfer_in' => 'Transfer (intrare)',
        'adjustment' => 'Ajustare',
        'write_off' => 'Casare',
        'return' => 'Retur',
    ];

    protected $fillable = [
        'company_id', 'part_id', 'batch_id', 'warehouse_id',
        'type', 'qty_delta', 'unit_cost',
        'ref_type', 'ref_id', 'user_id',
        'occurred_at', 'notes',
        'signature_b64', 'scan_payload',
    ];

    protected $casts = [
        'qty_delta' => 'decimal:3',
        'unit_cost' => 'decimal:2',
        'occurred_at' => 'datetime',
    ];

    public $timestamps = true;

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

    public function batch(): BelongsTo
    {
        return $this->belongsTo(PartBatch::class, 'batch_id');
    }

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

    public function ref(): MorphTo
    {
        return $this->morphTo();
    }
}
