<?php

namespace App\Models\Loyalty;

use App\Models\Concerns\BelongsToTenant;
use App\Models\Customers\Customer;
use App\Models\Lookups\LoyaltyTransactionType;
use App\Models\Sales\Invoice;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

/** Immutable append-only ledger. Never update or delete rows; only insert via LoyaltyService. */
class LoyaltyPointTransaction extends Model
{
    use BelongsToTenant;

    public const UPDATED_AT = null;

    protected $fillable = [
        'uuid', 'customer_id', 'program_id', 'invoice_id', 'loyalty_transaction_type_id',
        'points', 'balance_after', 'expires_at', 'description', 'is_reversed', 'reversed_at', 'created_by',
    ];

    protected function casts(): array
    {
        return [
            'points' => 'decimal:2',
            'balance_after' => 'decimal:2',
            'expires_at' => 'date',
            'is_reversed' => 'boolean',
            'reversed_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (self $transaction): void {
            if (! $transaction->uuid) {
                $transaction->uuid = (string) Str::ulid();
            }
        });
    }

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

    public function program(): BelongsTo
    {
        return $this->belongsTo(LoyaltyProgram::class, 'program_id');
    }

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

    public function type(): BelongsTo
    {
        return $this->belongsTo(LoyaltyTransactionType::class, 'loyalty_transaction_type_id');
    }

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