<?php

namespace App\Models;

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

/**
 * Stock adjustment document. Lives in two states:
 *
 *   - `draft`  → editable, nothing in the ledger yet
 *   - `posted` → items have been written to `stock_movements`, view-only.
 *                Corrections happen via a new offsetting adjustment so
 *                the ledger never loses history.
 *
 * Number format: `ADJ-YYYY-NNNN`, per-year sequence. Generated by
 * {@see \App\Actions\Inventory\GenerateStockAdjustmentNumber}.
 */
class StockAdjustment extends Model
{
    public const STATUS_DRAFT  = 'draft';
    public const STATUS_POSTED = 'posted';

    protected $fillable = [
        'store_id', 'number', 'adjustment_date',
        'reason_code_id', 'reason', 'notes',
        'status', 'posted_at',
        'created_by', 'updated_by',
    ];

    protected function casts(): array
    {
        return [
            'adjustment_date' => 'date',
            'posted_at'       => 'datetime',
        ];
    }

    public function isDraft(): bool  { return $this->status === self::STATUS_DRAFT; }
    public function isPosted(): bool { return $this->status === self::STATUS_POSTED; }

    /** @param Builder<StockAdjustment> $q */
    public function scopeDraft(Builder $q): void  { $q->where('status', self::STATUS_DRAFT); }

    /** @param Builder<StockAdjustment> $q */
    public function scopePosted(Builder $q): void { $q->where('status', self::STATUS_POSTED); }

    /** @return BelongsTo<Store, $this> */
    public function store(): BelongsTo
    {
        return $this->belongsTo(Store::class);
    }

    /** @return BelongsTo<StockAdjustmentReason, $this> */
    public function reasonCode(): BelongsTo
    {
        return $this->belongsTo(StockAdjustmentReason::class, 'reason_code_id');
    }

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

    /** @return BelongsTo<User, $this> */
    public function updater(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /** @return HasMany<StockAdjustmentItem, $this> */
    public function items(): HasMany
    {
        return $this->hasMany(StockAdjustmentItem::class);
    }
}
