<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;

class Media extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $table = 'media';

    protected $fillable = [
        'disk',
        'path',
        'filename',
        'original_name',
        'mime_type',
        'extension',
        'size',
        'width',
        'height',
        'folder',
        'title',
        'alt_text',
        'caption',
        'is_protected',
        'uploaded_by',
    ];

    protected $casts = [
        'is_protected' => 'boolean',
        'size' => 'integer',
        'width' => 'integer',
        'height' => 'integer',
    ];

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

    public function usages(): HasMany
    {
        return $this->hasMany(MediaUsage::class);
    }

    public function scopeOrdered($query)
    {
        return $query->latest('id');
    }

    public function url(): Attribute
    {
        return Attribute::get(fn (): string => Storage::disk($this->disk)->url($this->path));
    }

    public function getNameAttribute(): string
    {
        return $this->filename;
    }

    public function getMimeAttribute(): string
    {
        return $this->mime_type;
    }

    public function getDimensionsAttribute(): string
    {
        return $this->width && $this->height ? "{$this->width}×{$this->height}" : '—';
    }

    public function getUsedInAttribute(): string
    {
        return $this->is_protected ? 'Logo officiel protégé' : ($this->usages()->exists() ? 'Utilisé' : 'Non utilisé');
    }
}
