<?php

namespace App\Modules\ThreeCX\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Carbon\Carbon;

/**
 * 3CX OAuth2 Token Model
 * 
 * Stores access tokens, refresh tokens, and instance information
 */
class ThreeCXToken extends Model
{
    use SoftDeletes;
    
    protected $table = 'threecx_tokens';
    
    protected $fillable = [
        'user_id',
        'instance_id',
        'instance_name',
        'instance_url',
        'access_token',
        'refresh_token',
        'expires_at',
        'connected_at',
        'scopes'
    ];
    
    protected $casts = [
        'expires_at' => 'datetime',
        'connected_at' => 'datetime',
        'scopes' => 'array'
    ];
    
    protected $hidden = [
        'access_token',
        'refresh_token'
    ];
    
    /**
     * Get the user that owns the token
     */
    public function user()
    {
        return $this->belongsTo(\App\Models\User::class);
    }
    
    /**
     * Check if the token is expired
     */
    public function isExpired(): bool
    {
        return $this->expires_at && $this->expires_at->isPast();
    }
    
    /**
     * Check if the token expires soon (within 5 minutes)
     */
    public function expiresSoon(): bool
    {
        return $this->expires_at && $this->expires_at->subMinutes(5)->isPast();
    }
    
    /**
     * Get the number of minutes until expiry
     */
    public function minutesUntilExpiry(): ?int
    {
        if (!$this->expires_at) {
            return null;
        }
        
        return Carbon::now()->diffInMinutes($this->expires_at, false);
    }
    
    /**
     * Scope for active (non-expired) tokens
     */
    public function scopeActive($query)
    {
        return $query->where('expires_at', '>', Carbon::now());
    }
    
    /**
     * Scope for tokens by user
     */
    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }
    
    /**
     * Scope for tokens by instance
     */
    public function scopeForInstance($query, $instanceId)
    {
        return $query->where('instance_id', $instanceId);
    }
    
    /**
     * Scope for system tokens (no user)
     */
    public function scopeSystemTokens($query)
    {
        return $query->whereNull('user_id');
    }
    
    /**
     * Check if this is a system token
     */
    public function isSystemToken(): bool
    {
        return is_null($this->user_id);
    }
    
    /**
     * Check if token has specific scope
     */
    public function hasScope(string $scope): bool
    {
        return in_array($scope, $this->scopes ?? []);
    }
}