<?php

namespace App\Models\Products;

use App\Models\Auth\User;
use App\Models\Clients\Client;
use App\Models\Environments\Environment;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class LicenseToken extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'license_tokens';

    protected $fillable = [
        'name',
        'client_id',
        'created_by',
        'token',
        'active',
        'start_at',
        'end_at',
        'mode',
        'usage_limit',
        'metadata',
        'observation',
    ];

    protected $casts = [
        'active'   => 'boolean',
        'start_at' => 'datetime',
        'end_at'   => 'datetime',
        'metadata' => 'array',
    ];

    /*
    |--------------------------------------------------------------------------
    | Relaciones
    |--------------------------------------------------------------------------
    */

    /**
     * Cliente propietario del token.
     */
    public function client()
    {
        return $this->belongsTo(Client::class);
    }

    /**
     * Usuario que creó el token (auditoría).
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Productos asociados al token (pivot license_token_product).
     */
    public function products()
    {
        return $this->belongsToMany(
            Product::class,
            'license_token_product',
            'license_token_id',
            'product_id'
        )->withPivot([
            'mode',
            'status',
            'start_at',
            'end_at',
            'observation',
            'assigned_by',
        ])->withTimestamps();
    }

    /**
     * Entornos asociados a este token (1 token → N environments).
     */
    public function environments()
    {
        return $this->hasMany(Environment::class);
    }

    /*
    |--------------------------------------------------------------------------
    | Helpers
    |--------------------------------------------------------------------------
    */

    public function isActive(): bool
    {
        return $this->active === true;
    }

    public function isExpired(): bool
    {
        return $this->end_at && now()->greaterThan($this->end_at);
    }

    public function isValidNow(): bool
    {
        if (!$this->active) {
            return false;
        }

        if ($this->start_at && now()->lessThan($this->start_at)) {
            return false;
        }

        if ($this->end_at && now()->greaterThan($this->end_at)) {
            return false;
        }

        return true;
    }

    /**
     * Determina el estado de la licencia.
     * 
     * @return string 'activo'|'vencen_pronto'|'vencida'|'desactivada'
     */
    public function getStatus(): string
    {
        // Si la licencia no está activa
        if (!$this->active) {
            return 'desactivada';
        }

        // Si no tiene fecha de vencimiento, se considera activa
        if (!$this->end_at) {
            return 'activo';
        }

        $now = Carbon::now();
        $oneMonthFromNow = $now->copy()->addMonth();
        $endAt = Carbon::parse($this->end_at);

        // Verificar si está vencida (hoy o antes)
        if ($endAt->lte($now)) {
            return 'vencida';
        }

        // Verificar si vence pronto (dentro de un mes o menos, pero en el futuro)
        if ($endAt->lte($oneMonthFromNow)) {
            return 'vencen_pronto';
        }

        return 'activo';
    }
}

