<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Documento de inventario: entrada (recepción), entrega interna o salida agregada (ADR-002 v2).
 */
class InventoryTransferDocument extends Model
{
    protected $table = 'inventory_transfer_documents';

    public const TRANSFER_INBOUND_RECEIPT = 'inbound_receipt';

    public const TRANSFER_INTERNAL_DELIVERY = 'internal_delivery';

    public const TRANSFER_OUTBOUND = 'outbound';

    public const STATUS_DRAFT = 'draft';

    public const STATUS_CONFIRMED = 'confirmed';

    public const STATUS_CANCELLED = 'cancelled';

    protected $fillable = [
        'folio',
        'transfer_type',
        'status',
        'destination_area_id',
        'recipient_user_id',
        'supplier_id',
        'supplier_reference',
        'notes',
        'created_by',
        'confirmed_by',
        'confirmed_at',
        'cancelled_by',
        'cancelled_at',
    ];

    protected $casts = [
        'confirmed_at' => 'datetime',
        'cancelled_at' => 'datetime',
    ];

    public function destinationArea(): BelongsTo
    {
        return $this->belongsTo(Area::class, 'destination_area_id');
    }

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

    public function supplier(): BelongsTo
    {
        return $this->belongsTo(InventorySupplier::class, 'supplier_id');
    }

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

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

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

    public function lines(): HasMany
    {
        return $this->hasMany(InventoryTransferLine::class, 'inventory_transfer_document_id')
            ->orderBy('sort_order')
            ->orderBy('id');
    }
}
