<?php

namespace Modules\AppManager\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class DownloadToken extends Model
{
    use HasFactory;

    protected $table = 'am_download_tokens';

    protected $fillable = [
        'license_id',
        'token',
        'ip_address',
        'user_agent',
        'expires_at',
        'max_uses',
        'current_uses',
        'metadata',
    ];

    protected $casts = [
        'expires_at' => 'datetime',
        'metadata' => 'array',
    ];

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

    protected static function booted()
    {
        static::creating(function ($downloadToken) {
            if (empty($downloadToken->token)) {
                $downloadToken->token = Str::random(80); // Generate a strong random token
            }
        });
    }

    public function isExpired(): bool
    {
        return $this->expires_at->isPast();
    }

    public function isMaxUsesReached(): bool
    {
        return $this->current_uses >= $this->max_uses;
    }

    public function incrementUsage(): void
    {
        $this->increment('current_uses');
    }
}