<?php

namespace Modules\MedDocuments\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * Secure share link with expiry + revocation.
 */
class MeddocShare extends Model
{
    protected $table = 'meddoc_shares';

    protected $guarded = ['id'];

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

    public function document()
    {
        return $this->belongsTo(MeddocDocument::class, 'document_id');
    }

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

    public function isExpired(): bool
    {
        return $this->expires_at !== null && $this->expires_at->isPast();
    }

    /** A share is usable only if it is neither revoked nor expired. */
    public function isValid(): bool
    {
        return ! $this->isRevoked() && ! $this->isExpired();
    }

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