<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Downloads extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'episode_id',
        'type',
        'url',
    ];

    /**
     * Belongs to an episode
     */
    public function episode()
    {
        return $this->belongsTo(Episode::class);
    }

    /**
     * Convert bytes to human readable format
     */
    private static function bytesToHuman($bytes)
    {
        $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];

        for ($i = 0; $bytes > 1024; $i++) {
            $bytes /= 1024;
        }

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

    /**
     * Returns the human readable form of the file size
     */
    public function getFileSize(): ?string
    {
        return $this->size === null ? null : self::bytesToHuman($this->size);
    }
}
