<?php

namespace App\Models\Products;

use App\Models\Auth\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class LicenseTokenProduct extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'license_token_product';

    protected $fillable = [
        'license_token_id',
        'product_id',
        'mode',
        'status',
        'start_at',
        'end_at',
        'observation',
        'assigned_by',
    ];

    protected $casts = [
        'start_at' => 'datetime',
        'end_at'   => 'datetime',
    ];

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

    public function token()
    {
        return $this->belongsTo(LicenseToken::class, 'license_token_id');
    }

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function assignedBy()
    {
        return $this->belongsTo(User::class, 'assigned_by');
    }

    /*
    |--------------------------------------------------------------------------
    | Scopes útiles
    |--------------------------------------------------------------------------
    */

    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeForProductSlug($query, string $slug)
    {
        return $query->whereHas('product', function ($q) use ($slug) {
            $q->where('slug', $slug);
        });
    }

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

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

    public function isInDateRange(): bool
    {
        $now = now();

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

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

        return true;
    }

    public function isValidNow(): bool
    {
        return $this->isActive() && $this->isInDateRange();
    }
}

