<?php

namespace App\Models\Sales;

use App\Models\Branch;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Concerns\BranchScoped;
use App\Models\Customers\Customer;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * A cart suspended mid-sale so the cashier can serve another customer, then
 * resume it later. Deliberately NOT an Invoice — no stock movement, no
 * invoice number, no accounting entries happen until the sale is actually
 * completed at checkout.
 *
 * Deliberately not Auditable: the table only has `created_by` (who held it) —
 * structured audit trail entries (held/resumed/discarded) are written
 * explicitly by HeldSaleService instead.
 */
class HeldSale extends Model
{
    use BelongsToTenant, BranchScoped, SoftDeletes;

    protected $fillable = [
        'reference', 'branch_id', 'till_id', 'pos_session_id', 'customer_id',
        'discount_type', 'discount_value', 'note', 'held_at',
    ];

    protected function casts(): array
    {
        return [
            'discount_value' => 'decimal:2',
            'held_at' => 'datetime',
        ];
    }

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

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

    public function session(): BelongsTo
    {
        return $this->belongsTo(PosSession::class, 'pos_session_id');
    }

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

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

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