<?php

namespace App\Domain\Inventory\Models;

use App\Domain\Inventory\Enums\MovementDirection;
use App\Domain\Inventory\Enums\MovementType;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class InventoryMovement extends Model
{
    use BelongsToAcademy, HasUuid;

    protected $fillable = [
        'academy_id',
        'product_id',
        'warehouse_id',
        'movement_type',
        'direction',
        'quantity',
        'quantity_before',
        'quantity_after',
        'unit_cost',
        'total_cost',
        'reference_type',
        'reference_id',
        'batch_number',
        'expiry_date',
        'reason',
        'created_by',
        'metadata',
    ];

    protected function casts(): array
    {
        return [
            'movement_type' => MovementType::class,
            'direction' => MovementDirection::class,
            'quantity' => 'integer',
            'quantity_before' => 'integer',
            'quantity_after' => 'integer',
            'unit_cost' => 'integer',
            'total_cost' => 'integer',
            'expiry_date' => 'date',
            'metadata' => 'array',
        ];
    }

    // ─── Relationships ─────────────────────────────────────────

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

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

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

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

    // ─── Scopes ────────────────────────────────────────────────

    public function scopeForProduct(Builder $query, int $productId): Builder
    {
        return $query->where('product_id', $productId);
    }

    public function scopeForWarehouse(Builder $query, int $warehouseId): Builder
    {
        return $query->where('warehouse_id', $warehouseId);
    }

    public function scopeIncoming(Builder $query): Builder
    {
        return $query->where('direction', MovementDirection::In->value);
    }

    public function scopeOutgoing(Builder $query): Builder
    {
        return $query->where('direction', MovementDirection::Out->value);
    }

    public function scopeOfType(Builder $query, MovementType $type): Builder
    {
        return $query->where('movement_type', $type->value);
    }
}
