<?php

namespace App\Models\Inventory;

use App\Models\Branch;
use App\Models\Concerns\Auditable;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Concerns\BranchScoped;
use App\Models\Lookups\ReturnGrnStatus;
use App\Models\Purchasing\Supplier;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Return GRN ("Return to Supplier"): goods going back to a supplier, the
 * mirror of a GRN.
 *
 * Same lifecycle as Grn — create() only produces a DRAFT with its lines;
 * confirm() is the only thing that moves stock OUT (return_out movements),
 * consumes batch quantity, clears serials, and credits the supplier ledger
 * (outstanding balance drops); delete() is a STATUS change to DELETED that
 * reverses all of that (return_out_reversal + restock + serial restore +
 * supplier debit) when the document had already been confirmed.
 *
 * Deliberately no SoftDeletes — like Grn, a deleted return GRN stays visible
 * in the table with its status stamped, so the reversal trail is never
 * physically removed.
 */
class ReturnGrn extends Model
{
    use Auditable, BelongsToTenant, BranchScoped;

    protected $fillable = [
        'return_grn_number', 'branch_id', 'supplier_id',
        'reference', 'reason', 'note', 'total_cost',
        'return_grn_status_id', 'confirmed_by', 'confirmed_at',
        'deleted_by', 'deleted_at',
    ];

    protected function casts(): array
    {
        return [
            'return_grn_status_id' => 'integer',
            'total_cost' => 'decimal:2',
            'confirmed_at' => 'datetime',
            'deleted_at' => 'datetime',
        ];
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class, 'branch_id');
    }

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

    public function items(): HasMany
    {
        return $this->hasMany(ReturnGrnItem::class);
    }

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

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

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

    public function isDraft(): bool
    {
        return $this->return_grn_status_id === ReturnGrnStatus::DRAFT;
    }

    public function isConfirmed(): bool
    {
        return $this->return_grn_status_id === ReturnGrnStatus::CONFIRMED;
    }

    public function isDeleted(): bool
    {
        return $this->return_grn_status_id === ReturnGrnStatus::DELETED;
    }
}
