<?php

namespace Modules\MedDocuments\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * One physical file version of a document on the resolved disk.
 */
class MeddocVersion extends Model
{
    protected $table = 'meddoc_versions';

    public $timestamps = false;

    protected $guarded = ['id'];

    protected $casts = [
        'version_no' => 'integer',
        'size_bytes' => 'integer',
        'created_at' => 'datetime',
    ];

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

    public function isImage(): bool
    {
        return is_string($this->mime) && str_starts_with($this->mime, 'image/');
    }

    public function isPdf(): bool
    {
        return $this->mime === 'application/pdf'
            || strtolower(pathinfo($this->original_name, PATHINFO_EXTENSION)) === 'pdf';
    }

    public function humanSize(): string
    {
        $bytes = (int) $this->size_bytes;
        $units = ['B', 'KB', 'MB', 'GB'];
        $i = 0;
        while ($bytes >= 1024 && $i < count($units) - 1) {
            $bytes /= 1024;
            $i++;
        }

        return round($bytes, 1) . ' ' . $units[$i];
    }
}
