<?php

namespace App\Domain\Website\Models;

use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Domain\Website\Enums\MediaCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;

class Media extends Model
{
    use BelongsToAcademy, HasUuid, SoftDeletes;

    protected $table = 'media';

    protected $fillable = [
        'academy_id',
        'collection',
        'original_filename',
        'disk_path',
        'mime_type',
        'width',
        'height',
        'file_size',
        'alt_text',
        'alt_text_ar',
        'gallery_category',
        'mediable_type',
        'mediable_id',
        'sort_order',
    ];

    protected $casts = [
        'collection' => MediaCollection::class,
        'width' => 'integer',
        'height' => 'integer',
        'file_size' => 'integer',
        'sort_order' => 'integer',
    ];

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

    public function getUrlAttribute(): string
    {
        return Storage::disk('public')->url($this->disk_path);
    }

    public function getFileSizeHumanAttribute(): string
    {
        $bytes = $this->file_size;
        if ($bytes >= 1048576) {
            return round($bytes / 1048576, 1) . ' MB';
        }
        return round($bytes / 1024) . ' KB';
    }
}
