<?php

namespace Modules\MedPortal\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

/**
 * A temporary record-share grant to an external provider (SIFA Phase 8). Valid
 * while now() < expires_at AND revoked_at IS NULL.
 */
class MportalShareGrant extends Model
{
    protected $table = 'mportal_share_grants';

    protected $guarded = ['id'];

    protected $casts = [
        'expires_at' => 'datetime',
        'revoked_at' => 'datetime',
    ];

    public const SCOPES = ['records', 'appointments', 'full'];

    public static function newToken(): string
    {
        return Str::random(48);
    }

    public function getIsValidAttribute(): bool
    {
        if ($this->revoked_at !== null) {
            return false;
        }

        return $this->expires_at === null || $this->expires_at->isFuture();
    }

    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }

    public function scopeActive($query)
    {
        return $query->whereNull('revoked_at')
            ->where(function ($q) {
                $q->whereNull('expires_at')->orWhere('expires_at', '>', now());
            });
    }
}
