<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class StockAdjustment extends Model
{
    protected $fillable = [
        'product_id',
        'variant_id',
        'location_id',
        'adjustment_type',
        'before_qty',
        'adjusted_qty',
        'after_qty',
        'reason',
        'remarks',
        'reference_type',
        'reference_id',
        'created_by',
    ];

    public const TYPE_ADDITION = 'addition';
    public const TYPE_SUBTRACTION = 'subtraction';
    public const REFERENCE_AUDIT = 'audit';
    public const REFERENCE_MANUAL = 'manual';

    protected function casts(): array
    {
        return [
            'before_qty' => 'decimal:2',
            'adjusted_qty' => 'decimal:2',
            'after_qty' => 'decimal:2',
        ];
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class, 'product_id');
    }

    public function variant(): BelongsTo
    {
        return $this->belongsTo(Product::class, 'variant_id');
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function location(): BelongsTo
    {
        return $this->belongsTo(Location::class);
    }

    /**
     * Product row id that was adjusted (variant child id or single product id).
     */
    public function getEffectiveProductIdAttribute(): ?int
    {
        return $this->variant_id ?? $this->product_id;
    }
}
