<?php

namespace App\Models;

use App\Models\Concerns\BelongsToCompany;
use App\Models\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class ClientFile extends Model
{
    use HasFactory, SoftDeletes, BelongsToCompany, HasUuid;

    protected $fillable = [
        'uuid', 'company_id', 'clinical_history_id',
        'booking_id', 'uploaded_by',
        'type', 'title', 'description',
        'path', 'original_name', 'mime_type', 'size_bytes',
        'is_private', 'tags',
    ];

    protected function casts(): array
    {
        return [
            'is_private' => 'boolean',
            'tags'       => 'array',
            'size_bytes' => 'integer',
        ];
    }

    public function history(): BelongsTo
    {
        return $this->belongsTo(ClinicalHistory::class, 'clinical_history_id');
    }

    public function booking(): BelongsTo
    {
        return $this->belongsTo(Booking::class);
    }

    public function uploader(): BelongsTo
    {
        return $this->belongsTo(User::class, 'uploaded_by');
    }

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