<?php

namespace App\Modules\Inventory\Stock\Models;

use App\Modules\Admin\Tenancy\Traits\BelongsToTenant;
use App\Modules\Inventory\Models\Item;
use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Inventory\Models\WarehouseSection;
use App\Modules\Inventory\Stock\Support\InventoryStockMovementType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use RuntimeException;

/**
 * Append-only ledger row — updates and deletes are forbidden at runtime.
 */
class InventoryStockMovement extends Model
{
    use BelongsToTenant;

    public const UPDATED_AT = null;

    protected $table = 'inventory_stock_movements';

    protected $fillable = [
        'tenant_id',
        'warehouse_id',
        'item_id',
        'warehouse_section_id',
        'movement_type',
        'quantity',
        'unit_id',
        'occurred_at',
        'recorded_at',
        'actor_user_id',
        'correlation_id',
        'idempotency_key',
        'idempotency_source',
        'reference_type',
        'reference_id',
        'metadata',
        'reverses_movement_id',
    ];

    protected function casts(): array
    {
        return [
            'movement_type' => InventoryStockMovementType::class,
            'quantity' => 'decimal:8',
            'occurred_at' => 'datetime',
            'recorded_at' => 'datetime',
            'metadata' => 'array',
        ];
    }

    protected static function booted(): void
    {
        static::updating(function (): void {
            throw new RuntimeException('inventory_stock_movements is immutable.');
        });

        static::deleting(function (): void {
            throw new RuntimeException('inventory_stock_movements cannot be deleted.');
        });
    }

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

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

    public function warehouseSection(): BelongsTo
    {
        return $this->belongsTo(WarehouseSection::class, 'warehouse_section_id');
    }
}
