<?php

namespace App\Models\Tenants;

use App\Traits\Auditable;
use App\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class StockLot extends Model
{
    use Auditable, BelongsToTenant, SoftDeletes;

    protected $fillable = [
        'tenant_id',
        'stock_id',
        'lot_no',
        'fifo_order',
        'receipt_date',
        'qty',
        'reserved_qty',
        'available_qty',
        'unit',
        'supplier',
        'supplier_lot',
        'po_number',
        'location',
        'status',
        'receiving_id',
        'work_order_id',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    protected $casts = [
        'fifo_order' => 'integer',
        'receipt_date' => 'date',
        'qty' => 'decimal:3',
        'reserved_qty' => 'decimal:3',
        'available_qty' => 'decimal:3',
        'stock_id' => 'integer',
        'receiving_id' => 'integer',
        'work_order_id' => 'integer',
    ];

    /**
     * LOT 상태 목록
     */
    public const STATUSES = [
        'available' => '사용가능',
        'reserved' => '예약됨',
        'used' => '사용완료',
    ];

    /**
     * 재고 관계
     */
    public function stock(): BelongsTo
    {
        return $this->belongsTo(Stock::class);
    }

    /**
     * 입고 관계
     */
    public function receiving(): BelongsTo
    {
        return $this->belongsTo(Receiving::class);
    }

    /**
     * 작업지시 관계 (생산입고)
     */
    public function workOrder(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Production\WorkOrder::class);
    }

    /**
     * 생성자 관계
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Members\User::class, 'created_by');
    }

    /**
     * 상태 라벨
     */
    public function getStatusLabelAttribute(): string
    {
        return self::STATUSES[$this->status] ?? $this->status;
    }

    /**
     * 경과일
     */
    public function getDaysElapsedAttribute(): int
    {
        return $this->receipt_date->diffInDays(now());
    }

    /**
     * 가용 수량 업데이트
     */
    public function updateAvailableQty(): void
    {
        $this->available_qty = $this->qty - $this->reserved_qty;

        if ($this->available_qty <= 0 && $this->qty <= 0) {
            $this->status = 'used';
        } elseif ($this->reserved_qty > 0) {
            $this->status = 'reserved';
        } else {
            $this->status = 'available';
        }

        $this->save();
    }
}
