<?php

namespace App\Models;

use App\Enums\RedemptionStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Veelasky\LaravelHashId\Eloquent\HashableId;

class Redemption extends Model
{
    use HasFactory, HashableId, SoftDeletes;

    protected $guarded = ['id'];

    protected function casts(): array
    {
        return [
            'status' => RedemptionStatus::class,
            'points_spent' => 'int',
            'expires_at' => 'datetime',
            'verified_at' => 'datetime',
        ];
    }

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

    public function reward(): BelongsTo
    {
        return $this->belongsTo(Reward::class)->withTrashed();
    }

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

    public function isExpired(): bool
    {
        if ($this->status === RedemptionStatus::EXPIRED) {
            return true;
        }

        if ($this->expires_at->isPast()) {
            if ($this->status === RedemptionStatus::WAITING_PICKUP) {
                $this->update(['status' => RedemptionStatus::EXPIRED]);
            }

            return true;
        }

        return false;
    }
}
