<?php

namespace App\Modules\Xero\Models;

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

/**
 * Xero OAuth2 Token Model
 * 
 * Stores access tokens, refresh tokens, and tenant information
 */
class XeroToken extends Model
{
    use SoftDeletes;
    
    protected $table = 'xero_tokens';
    
    protected $fillable = [
        'user_id',
        'tenant_id',
        'tenant_name',
        'tenant_type',
        'access_token',
        'refresh_token',
        'expires_at',
        'connected_at'
    ];
    
    protected $dates = [
        'expires_at',
        'connected_at',
        'deleted_at',
        'created_at',
        'updated_at'
    ];
    
    protected $casts = [
        'expires_at' => 'datetime',
        'connected_at' => 'datetime'
    ];
    
    /**
     * 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()
    {
        return $this->expires_at && $this->expires_at->isPast();
    }
    
    /**
     * Check if the token expires soon (within 5 minutes)
     */
    public function expiresSoon()
    {
        return $this->expires_at && $this->expires_at->subMinutes(5)->isPast();
    }
    
    /**
     * Get the number of minutes until expiry
     */
    public function minutesUntilExpiry()
    {
        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 tenant
     */
    public function scopeForTenant($query, $tenantId)
    {
        return $query->where('tenant_id', $tenantId);
    }
} 