<?php

namespace Modules\AppManager\Entities;

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

class License extends Model
{
    use HasFactory;

    protected $table = 'am_licenses';

    protected $fillable = [
        'managed_script_id',
        'license_key',
        'type',
        'customer_email',
        'customer_name', // This was already here, good.
        'purchase_code',
        'activation_limit',
        'current_activations',
        'status',
        'expires_at',
        'supported_until',
        'metadata',
    ];

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

    protected static function newFactory()
    {
        // return \Modules\AppManager\Database\factories\LicenseFactory::new();
    }

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

    public function activationLogs(): HasMany
    {
        return $this->hasMany(ActivationLog::class);
    }

    protected static function booted()
    {
        static::creating(function ($license) {
            if (empty($license->license_key)) {
                // Generate a more robust key, e.g., prefix + UUID
                $prefix = strtoupper(Str::slug($license->managedScript->name ?? 'LIC', '_'));
                $license->license_key = $prefix . '_' . Str::uuid()->toString();
            }
        });
    }

    public function getActiveDomains(): \Illuminate\Support\Collection
    {
        return $this->activationLogs()
                    ->where('status', 'success')
                    ->distinct('activated_domain') // Ensure we only get unique domains
                    ->pluck('activated_domain');
    }
}