<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class AdminDocument extends Model
{
    protected $fillable = [
        'name',
        'original_filename',
        'file_path',
        'file_size',
        'mime_type',
        'extension',
        'description',
        'uploaded_by',
    ];

    protected $casts = [
        'file_size' => 'integer',
    ];

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

    /**
     * Human-readable file size (e.g. "1.2 MB").
     */
    public function getFileSizeFormattedAttribute(): string
    {
        $bytes = $this->file_size;

        if ($bytes < 1024) {
            return $bytes . ' B';
        } elseif ($bytes < 1048576) {
            return round($bytes / 1024, 1) . ' KB';
        } elseif ($bytes < 1073741824) {
            return round($bytes / 1048576, 1) . ' MB';
        }

        return round($bytes / 1073741824, 2) . ' GB';
    }

    /**
     * Authenticated download URL for this document.
     * Files are on the private kyc disk — direct storage access is not possible.
     */
    public function getUrlAttribute(): ?string
    {
        return $this->id ? url('/api/admin/documents/' . $this->id . '/download') : null;
    }
}
