<?php

declare(strict_types=1);

namespace App\Models;

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

class Upload extends Model
{
    protected $guarded = [];

    protected function casts(): array
    {
        return [
            'size_bytes' => 'integer',
            'confirmed_at' => 'immutable_datetime',
        ];
    }

    public function uploadable(): MorphTo
    {
        return $this->morphTo();
    }

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

    public function scopeOfKind(Builder $query, string $kind): Builder
    {
        return $query->where('kind', $kind);
    }

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

    /** Human size, for a screen where the exact byte count helps nobody. */
    public function humanSize(): string
    {
        $bytes = $this->size_bytes;

        if ($bytes === null) {
            return '—';
        }

        foreach ([['GB', 1024 ** 3], ['MB', 1024 ** 2], ['KB', 1024]] as [$unit, $step]) {
            if ($bytes >= $step) {
                return round($bytes / $step, 1).' '.$unit;
            }
        }

        return $bytes.' B';
    }
}
