<?php

namespace Artemis\Loyalty\Concerns;

use Artemis\Loyalty\Models\PointTransaction;
use Artemis\Loyalty\Models\Redemption;
use Illuminate\Support\Facades\Cache;

trait HasLoyalty
{
    public function loyaltyPoints()
    {
        return $this->hasMany(PointTransaction::class);
    }

    public function redemptions()
    {
        return $this->hasMany(Redemption::class);
    }

    public function getLoyaltyBalanceAttribute(): int
    {
        return Cache::remember("user:{$this->id}:loyalty_balance", 60, function () {
            return $this->loyaltyPoints()->sum('points');
        });
    }

    public function hasEnoughPoints(int $cost): bool
    {
        return $this->loyalty_balance >= $cost;
    }

    public function addPoints(int $amount, string $type = 'manual', ?string $sourceId = null): void
    {
        $this->loyaltyPoints()->create([
            'points' => $amount,
            'type' => $type,
            'source_id' => $sourceId,
            'expires_at' => now()->addDays((int) config('loyalty.points.point_expiry_days', 365)),
        ]);
        Cache::forget("user:{$this->id}:loyalty_balance");
    }

    public function spendPoints(int $amount): void
    {
        // Optional: logic for deducting or soft spending
        Cache::forget("user:{$this->id}:loyalty_balance");
    }
}

