<?php

namespace App\Models\Loyalty;

use App\Models\Concerns\Auditable;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class LoyaltyProgram extends Model
{
    use Auditable, BelongsToTenant;

    protected $fillable = [
        'uuid', 'name', 'base_earn_rate', 'redemption_rate',
        'minimum_purchase_to_earn', 'minimum_points_to_redeem', 'points_validity_days',
        'is_active', 'started_at', 'ended_at', 'created_by', 'updated_by',
    ];

    protected function casts(): array
    {
        return [
            'base_earn_rate' => 'decimal:4',
            'redemption_rate' => 'decimal:4',
            'minimum_purchase_to_earn' => 'decimal:2',
            'minimum_points_to_redeem' => 'decimal:2',
            'points_validity_days' => 'integer',
            'is_active' => 'boolean',
            'started_at' => 'date',
            'ended_at' => 'date',
        ];
    }

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

    public function tiers(): HasMany
    {
        return $this->hasMany(LoyaltyTier::class, 'program_id')->orderBy('sort_order');
    }

    public function balances(): HasMany
    {
        return $this->hasMany(CustomerLoyaltyBalance::class, 'program_id');
    }
}
