<?php

namespace App\Models\Loyalty;

use App\Models\Concerns\Auditable;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Customers\Customer;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class CustomerLoyaltyBalance extends Model
{
    use Auditable, BelongsToTenant;

    protected $fillable = [
        'uuid', 'customer_id', 'program_id', 'tier_id', 'points_balance',
        'lifetime_points', 'tier_evaluated_at', 'created_by', 'updated_by',
    ];

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

    protected static function booted(): void
    {
        static::creating(function (self $balance): void {
            if (! $balance->uuid) {
                $balance->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 tier(): BelongsTo
    {
        return $this->belongsTo(LoyaltyTier::class, 'tier_id');
    }
}
