<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class EmailMessageAttachment extends Model
{
    protected $fillable = ['email_message_id', 'disk', 'path', 'name', 'size'];
    protected $appends = ['public_url', 'is_image', 'size_human'];

    public function message()
    {
        return $this->belongsTo(EmailMessage::class);
    }

    public function getPublicUrlAttribute(): ?string
    {
        if (!$this->disk || !$this->path) return null;
        return Storage::disk($this->disk)->url($this->path);
    }

    public function getIsImageAttribute(): bool
    {
        $ext = strtolower(pathinfo($this->name ?: $this->path, PATHINFO_EXTENSION));
        return in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg']);
    }

    public function getSizeHumanAttribute(): ?string
    {
        if (!$this->size) return null;
        $kb = $this->size / 1024;
        return $kb >= 1024
            ? number_format($kb / 1024, 2) . ' MB'
            : number_format($kb, 1) . ' KB';
    }
}
