<?php

namespace App\Modules\Office365\Models;

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

class Office365Token extends Model
{
    protected $table = 'office365_tokens';
    
    protected $fillable = [
        'user_id',
        'access_token',
        'refresh_token',
        'expires_at',
        'scope',
        'token_type'
    ];

    protected $dates = ['expires_at'];
    
    protected $casts = [
        'expires_at' => 'datetime'
    ];

    public function user()
    {
        return $this->belongsTo(\App\Models\User::class);
    }

    /**
     * Check if the access token is expired
     */
    public function isExpired()
    {
        return $this->expires_at && $this->expires_at->isPast();
    }

    /**
     * Check if the access token will expire soon (within 5 minutes)
     */
    public function willExpireSoon()
    {
        return $this->expires_at && $this->expires_at->subMinutes(5)->isPast();
    }

    /**
     * Get the token for a specific user
     */
    public static function forUser($userId)
    {
        return static::where('user_id', $userId)->first();
    }
}